Equilibrium Point in Java: Algorithm & Practice

Find index where left sum equals right sum

Problem summary

Find an index where sum of elements to the left equals sum of elements to the right.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 2, 2}; // Test case 1
        
        // Find equilibrium index
        // Print: Index: <i> OR No equilibrium
    }
}

Expected output and test cases

  • 1+3 = 2+2 at index 2
    Index: 2
  • Left sum 0 = right sum 0
    Index: 0
  • No valid index
    No equilibrium

Hints

  1. Calculate total sum first
  2. Iterate: leftSum, rightSum = total - leftSum - arr[i]
  3. Check if equal at each index

How to approach the problem

Compute the total array sum first. As you scan from left to right, subtract the current value from the remaining right-side sum, compare it with the running left-side sum, then add the current value to the left-side sum.

Time and space complexity

Time: O(n). Space: O(1).

Constraints

  • The input must be a finite integer array.
  • An index at either end is valid when the elements on the opposite side sum to zero.

Common mistakes

  • Including the current element in either the left or right sum.
  • Returning an array value instead of its zero-based index.
  • Recomputing both sums for every index, which turns the solution into O(n²).

Related Arrays exercises

Practice all Arrays exercises · Run this idea in the Java compiler