Advertisement
Home Data Structure Arrays Find the Equilibrium Index of an Array

Find the Equilibrium Index of an Array

0
Advertisement

Title: Find the Equilibrium Index of an Array

An equilibrium index of an array is a position where the sum of all elements to its left equals the sum of all elements to its right. It is a classic array problem that interviewers like because the brute force solution is easy to write, but the efficient one requires you to notice a simple running sum trick.

In this guide, you’ll learn how to find the equilibrium index of an array in Java using a single pass over the array. Let’s explore the approach step by step, trace the algorithm on a real array, and work through examples, common mistakes, edge cases, and interview follow-up questions so you are ready to discuss this problem in depth.

Understanding the Problem

Given an array of integers, an equilibrium index is an index i such that the sum of the elements before index i equals the sum of the elements after index i. The element at index i itself is not included in either sum.

For example, in the array {-7, 1, 5, 2, -4, 3, 0}, index 3 is an equilibrium index because the sum of the elements before it, -7 + 1 + 5, equals -1, and the sum of the elements after it, -4 + 3 + 0, also equals -1.

Some arrays have no equilibrium index at all, and some can have more than one. In this guide, we return the first equilibrium index found while scanning from left to right.

Approach / Algorithm Steps

The brute force approach recomputes the left and right sums for every index, which costs O(n^2) time. We can do better by tracking a running sum instead.

  1. Compute the totalSum of all elements in the array with a single pass.
  2. Initialize leftSum to 0; it tracks the running sum of elements before the current index.
  3. Loop over the array from index 0 to numbers.length - 1.
  4. For each index i, compute rightSum as totalSum - leftSum - numbers[i], which is the sum of everything after index i.
  5. Compare leftSum and rightSum. If they are equal, index i is an equilibrium index, so return it immediately.
  6. Otherwise, add numbers[i] to leftSum and move to the next index.
  7. If the loop finishes without finding a match, return -1 to signal that no equilibrium index exists.

Java Program

The following program implements the running sum approach in a single pass over the array.

Java
public class EquilibriumIndex {

    public static int findEquilibriumIndex(int[] numbers) {
        int totalSum = 0;
        for (int num : numbers) {
            totalSum += num;
        }

        int leftSum = 0;
        for (int i = 0; i < numbers.length; i++) {
            int rightSum = totalSum - leftSum - numbers[i];
            if (leftSum == rightSum) {
                return i;
            }
            leftSum += numbers[i];
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] numbers = {-7, 1, 5, 2, -4, 3, 0};
        int index = findEquilibriumIndex(numbers);

        if (index != -1) {
            System.out.println("Equilibrium index found at index: " + index);
        } else {
            System.out.println("No equilibrium index exists in this array.");
        }
    }
}

Explanation of the Program

The findEquilibriumIndex method first sums every element into totalSum using a simple for-each loop.

It then walks the array a second time with a plain indexed loop. At each index i, it derives rightSum directly from totalSum and leftSum instead of summing the remaining elements again, which keeps the method at O(n) instead of O(n^2).

The moment leftSum equals rightSum, the method returns the current index. If the loop finishes without a match, it returns -1.

The main method runs the function against the sample array {-7, 1, 5, 2, -4, 3, 0} and prints the result, or a message explaining that no equilibrium index exists.

Step-by-Step Trace

Let’s trace findEquilibriumIndex on the array {1, 2, 3, 4, 6}, which has totalSum = 16 and an equilibrium index at 3.

inumbers[i]leftSum (before)rightSumleftSum == rightSum?leftSum (after)
01015no1
12113no3
23310no6
3466yes (returns 3)–

After each iteration that does not return, leftSum holds the exact sum of numbers[0..i], which is why comparing it against the freshly derived rightSum on the next index always reflects the correct split point.

Examples

Example 1: No Equilibrium Index Exists

A strictly increasing array of positive numbers never balances, because the left side is always lighter than the right side until the array runs out.

Java
int[] numbers = {1, 2, 3, 4, 5};
int result = findEquilibriumIndex(numbers);
System.out.println(result); // Output: -1

Example 2: Equilibrium Index With Negative Numbers

Negative numbers can bring the two sides back into balance even when the array is not symmetric in length.

Java
int[] numbers = {4, 2, -6, 3, 1, 2};
int result = findEquilibriumIndex(numbers);
System.out.println(result); // Output: 2

Example 3: Single-Element Array

A single-element array is always an equilibrium at index 0, since both the left sum and the right sum are empty sums equal to 0.

Java
int[] numbers = {5};
int result = findEquilibriumIndex(numbers);
System.out.println(result); // Output: 0

Common Mistakes to Avoid

These are the mistakes that most often turn a correct-looking solution into a wrong answer on this specific problem.

  • Recomputing the right sum with nested loops – summing numbers[i+1..n-1] inside the outer loop turns the algorithm into O(n^2) and times out on large inputs. Precompute totalSum once and derive rightSum from it.
  • Forgetting to exclude numbers[i] from rightSum – computing rightSum as totalSum - leftSum without subtracting numbers[i] double counts the current element, so the comparison never succeeds even on arrays that do have an equilibrium index. Subtract numbers[i] explicitly.
  • Updating leftSum before the comparison – adding numbers[i] to leftSum before checking leftSum == rightSum silently compares the wrong index and can skip the true equilibrium index. Always compare first, then update leftSum.
  • Confusing index 0 with “no equilibrium found” – using 0 as both a valid equilibrium index and the “not found” signal makes the caller unable to tell them apart. Reserve -1 exclusively for “not found”.
  • Ignoring overflow on large arrays – summing millions of large magnitude elements into an int totalSum wraps around silently and produces a wrong equilibrium index. Use long for the running sums when the input size or magnitude is unbounded.

Edge Cases to Test

Walk through these input shapes before you consider the solution done; interviewers notice when you raise them unprompted.

  • Empty array
  • Single-element array
  • All identical elements
  • Equilibrium index at position 0
  • Equilibrium index at the last valid position
  • No equilibrium index exists
  • Large magnitude elements causing overflow
  • Null array reference

Additional Considerations

The running sum approach runs in O(n) time: one pass to compute totalSum and one pass to find the equilibrium index. It uses O(1) extra space beyond the input array, since only totalSum, leftSum, and the loop index are needed.

An alternative is to precompute a prefix sum array up front and look up each side’s sum by subtraction. That is also O(n) time but costs O(n) extra space, so the running sum version is the better default unless you need random access to arbitrary prefix sums elsewhere in your code.

Watch the overflow edge case closely: if the array holds values near Integer.MAX_VALUE, summing enough of them into an int wraps around and produces a totalSum that no longer reflects the real total, which then reports a wrong or missing equilibrium index. A null array reference is a simpler but equally real failure mode; the method as written throws a NullPointerException on the for-each loop if numbers is null, so callers should guard against that before invoking it.

Interview Follow-up Questions

Once you have the base solution working, expect an interviewer to push further with variations like these.

  • What if you need every equilibrium index, not just the first? – continue the same loop past the first match and collect each index whose leftSum equals rightSum into a list instead of returning immediately.
  • What if the array can contain values near Integer.MIN_VALUE or Integer.MAX_VALUE? – switch totalSum and leftSum to long so the intermediate subtraction never overflows before the comparison runs.
  • What if you must solve it using only O(1) extra memory on an array you cannot modify? – this is already true of the running sum approach: besides totalSum, leftSum, and the loop index, no auxiliary array is ever allocated.
  • What if the input arrives as a stream and you cannot look at it twice? – the running sum trick needs the full totalSum before it can test the first index, so you would need to buffer the stream or make two passes once the full length is known.
  • What if there are billions of elements spread across multiple machines? – compute a partial sum on each shard, combine them into a global totalSum, then have each shard rescan its own partition with the already known prefix offset to test the equilibrium condition locally.

Conclusion

Finding the equilibrium index of an array is a great example of trading a second array or a nested loop for a single running sum. Once you see that rightSum can be derived from totalSum and leftSum, the whole problem collapses into one clean O(n) pass.

Try adapting the program to return every equilibrium index, or to work with long values, to make sure the idea has fully sunk in. You can learn more about array algorithms like this one in our Arrays category.