Wednesday, February 23, 2011

Equilibrium index of an Array

Ques :What is "Equilibrium index of an Array" ?
Ans:   Equilibrium index of an Array is an index of Array, such that the sum of elements at lower indices is equal to the sum of elements at higher indices. Value of element at the index is not taken into account.
For example, In the below Array:
Array-7   1    5    -4    3   0
Index        0   1    2   3   4    5   6
So here Index 3 and 6 are equilibrium index.
3 is an equilibrium index, because:     A[0]+A[1]+A[2]  = A[4]+A[5]+A[6]
6 is also an equilibrium index, because: A[0]+A[1]+A[2]+A[3]+A[4]+A[5] = 0

Method-1: Brute-Force method
 This method uses two loops to find the leftSum and rightSum for each index while traversing the array. 
void printEquilibriumIndexes(int arr[], int n){
    for (int i = 0; i < n; ++i){
        int leftSum = 0, rightSum = 0;
        for (int j=0; j<i; j++)
            leftSum += arr[j];
        for(int j=i+1; j<n; j++)
            rightSum += arr[j];       
        if (leftSum == rightSum)
           System.out.println("Index : "+i);
    }
}

Time complexity: O(n^2) 
Method-2: In this more efficient method where we keep track of the sum of all the elements in the Array and hence do not calculate the leftSum and rightSum from scratch but just update them based on the current index.
/**
 * This function will print all the Equilibrium Indexes in array arr
 */
void printEquilibriumIndexes(int arr[], int n){
    int rightSum = 0;   // Sum of all the Elements to the right of an Element
    int leftSum = 0; // Sum of all the Elements to the left of an Element

    for (int i=0; i<n; ++i)
        rightSum += arr[i];

    for (int i = 0; i < n; ++i){
        rightSum -= arr[i];
        if (leftSum == rightSum)
           System.out.println("Index: "+i);

        leftSum += arr[i];
    }
}

1 comment:

  1. hello sir,
    sir can u provide the program in which we can count the quotes of the string.
    reply
    on manojkjsce@gmail.com

    ReplyDelete