Find Equilibrium Index of an Array

Share

Problem: Given an array of N integers. You have to find the equilibrium index in this array. Please note – an equilibrium index is that index of an array where sum of elements to the left of that index is equal to sum of elements to the right of that index.

Problem Explanation: You are given an array a ={-7, 1, 5, 2, -4, 3, 0} – So, here sum of elements to the left of 2 are equal to sum of elements to its right. Similarly, sum of elements to the left of 0 are equal to 0 (please note, sum of elements to the right of 0 are also equal to 0 as there is not element present to its right). Hence, 3 [array index for element 2] and 6 [array index for element 0] are equilibrium index of a.

Java Implementation


public void findIndexEquilibrium(int A[], int n) { 

    int sumOfArrayElements = 0; 
    int leftSum = 0; 

    for (int i = 0; i < n; i++) { 
        sumOfArrayElements = sumOfArrayElements + A[i]; 
    } 
    
    for (int i = 0; i < n; i++) { 
        sumOfArrayElements -= A[i]; 
        if (sumOfArrayElements == leftSum) { 
            System.out.println(&quot;Equilibrium index of A[]:&quot; + i); 
        } 
        leftSum += A[i]; 
    } 
}

Time Complexity: O(n) 

Note: If you find any other better way to approach to this problem or you find any issue/error in above code snippets/approaches – please share it in the comments section below and get a chance to enrol free of cost for an online Live Data Structure and Algorithm course (specially designed for interview preparation for software companies like Amazon, Google, Facebook, FlipKart, SnapDeal, HealthKart…)