Program to find the Equilibrium index of an array

Equilibrium index of an array is the index such that the sum of its lower index values and the sum of its higher index values are same.

Suppose the array values are a[0]=1  a[1]=-5  a[2]=4  a[3]=4  a[4]=-6  a[5]=5  a[6]=1 then the index 3 will be at Equilibrium because a[0]+a[1]+a[2]=a[4]+a[5]+a[6].In an array there can be more then one Equilibrium indexes provided the sum of its lower indexes and higher indexes are same.

The logic of the program is pretty simple.First we will calculate the sum of the whole array elements and then initialize leftsum=0.Now we iterate through all the index of the arrays and substract all index values from the sum and add to leftsum and simultaneously check whether sum=leftsum.If it is found out equal then return i that is the index of the array.

Program :


#include <stdio.h>
#include<conio.h>


int equilibrium(int arr[], int len)
{
   int sum = 0;    
   int leftsum = 0;
   int i;

 
   for (i = 0; i < len; ++i)           // Find sum of the whole array
        sum = sum+arr[i]

   for( i = 0; i < len; ++i)
   {
      sum = sum-arr[i]                // Substract array values from sum starting from first index to get rightsum

      if(leftsum == sum)              // Compare leftsum and rightsum if same return i
        return i;

      leftsum = leftsum+arr[i];      // Add array elements to leftsum
   }

   
    return -1;                             // If no equilibrium index found, then return -1
} 


int main()
{
  int a[] = {1,-5,4,4,-6,5,1};
  int size = sizeof(arr)/sizeof(arr[0]);
  printf("equilibrium index is %d\n", equilibrium(a, size));
  getch();

}

Comments

Popular posts from this blog

Tricky Questions or Puzzles in C

Program to uncompress a string ie a2b3c4 to aabbbcccc

Programs and Puzzles in technical interviews i faced