Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Arrays

Equilibrium Index

Easy · Arrays · Asked at Amazon, Adobe, TCS, Infosys, Wipro

An index i (0-based) is an equilibrium index if the sum of the elements before it equals the sum of the elements after it. (An empty side has sum 0.)

Print the smallest equilibrium index, or -1 if there is none.

Input

First line: n. Second line: n space-separated integers.

Output

The smallest equilibrium index, or -1.

Constraints

Keep the total. Walking left to right with a running left sum, the right sum is total − left − a[i].

Example 1

Input

7
-7 1 5 2 -4 3 0

Output

3

Example 2

Input

3
1 2 3

Output

-1

Hints

  1. Computing the left and right sums from scratch for every i is O(n²).
  2. If you know the total and the sum to the left of i, the right sum is total − left − a[i].

Approach

Add up the whole array once. Then walk left to right keeping the running sum of the elements before i. At each index the right side is total − left − a[i]; the first index where the two sides match is the answer. Add a[i] to the left sum after checking.

Complexity: O(n) time · O(1) extra space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<long long> a(n);
    long long total = 0;
    for (auto &x : a) {
        cin >> x;
        total += x;
    }
    long long left = 0;
    for (int i = 0; i < n; i++) {
        if (left == total - left - a[i]) {
            cout << i << "\n";
            return 0;
        }
        left += a[i];
    }
    cout << -1 << "\n";
    return 0;
}

Python solution

import sys

data = sys.stdin.read().split()
n = int(data[0])
a = list(map(int, data[1 : 1 + n]))
total = sum(a)
left = 0
answer = -1
for i, x in enumerate(a):
    if left == total - left - x:
        answer = i
        break
    left += x
print(answer)

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        long[] a = new long[n];
        long total = 0;
        for (int i = 0; i < n; i++) {
            in.nextToken();
            a[i] = (long) in.nval;
            total += a[i];
        }
        long left = 0;
        for (int i = 0; i < n; i++) {
            if (left == total - left - a[i]) {
                System.out.println(i);
                return;
            }
            left += a[i];
        }
        System.out.println(-1);
    }
}

Solve Equilibrium Index online · All practice problems