VOOZH about

URL: https://www.geeksforgeeks.org/dsa/equilibrium-index-of-an-array/

⇱ Equilibrium Index - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Equilibrium Index

Last Updated : 13 Feb, 2026

Given an array arr[] of size n, find an equilibriumindex (if any) or -1 if no equilibrium index exists. The equilibrium index of an array is an index such that the sum of all elements at lower indexes equals the sum of all elements at higher indexes. When the index is at the start of the array, the left sum is 0, and when it's at the end, the right sum is 0.

Note: If multiple equilibrium indices exist, return the first one encountered from left to right.

Examples:

Input: arr[] = [1, 2, 0, 3]
Output: 2
Explanation: The sum on the left of index 2 is 1 + 2 = 3 and sum on the right of index 2 is 3.

Input: arr[] = [1, 1, 1, 1]
Output: -1
Explanation: There is no equilibrium index in the array.

Input: arr[] = [-7, 1, 5, 2, -4, 3, 0]
Output: 3
Explanation: The sum on the left of index 3 is -7 + 1 + 5 = -1 and sum on the right of index 3 is -4 + 3 + 0 = -1.

[Naive Approach] Using Nested Loop - O(n2) Time and O(1) Space

The most basic idea is to use nested loops. The outer loop iterates through all the indices one by one. Consider it as equilibrium index. The inner loop finds out whether index i is equilibrium index or not, by checking if left side sum = right side sum.


Output
3

[Better Approach] Prefix Sum and Suffix Sum Array - O(n) Time and O(n) Space

The idea is to remove the need of inner loop. Instead of calculating the left side sum and right side sum each time, precompute the prefix sum array and suffix sum array, and simply access this in O(1) time.
So for each index i, we can check if prefixSum[i - 1] = suffixSum[i + 1] but to avoid unnecessary boundary checks we can also check if prefixSum[i] = suffixSum[i].


Output
3

[Expected Approach] Running Prefix Sum and Suffix Sum - O(n) Time and O(1) Space

Now the above prefix sum array and suffix sum array approach can be further optimized in terms of space, by using prefix sum and suffix sum variables.

The idea is that instead of storing the prefix sum and suffix sum for each element in an array, we can simply use the fact that
Sum(arr[0 : pivot - 1]) + arr[pivot] + Sum(arr[pivot + 1: n - 1]) = totalSum
so, Sum(arr[pivot + 1: n - 1]) = totalSum - Sum(arr[0 : pivot - 1]) - arr[pivot] .
Here, pivot refers to the index that we are currently checking for the equilibrium index.


Output
3


Comment