PROBLEM
A zero-indexed array A consisting of N integers is given. An equilibrium index of this array is any integer P such that 0 ≤ P < Nand the sum of elements of lower indices is equal to the sum of elements of higher indices.
A[0] + A[1] + ... + A[P−1] = A[P+1] + ... + A[N−2] + A[N−1].
Sum of zero elements is assumed to be equal to 0. This can happen if P = 0 or if P = N−1.
Range of N: [0 ... 100,000].
Elements Range: [−2,147,483,648 ... 2,147,483,647].
Complexity: worst-case time O(N)
MY 5-MIN SOLUTION
This is the intuitive solution by computing the formula performance is O(N^2) as it sums the all array for each iteration and it doesnt work for large entries.
def solution(A):
result = []
for i in xrange(len(A)):
if sum(A[:i]) == sum(A[i+1:]):
result.append(i)
if result == []:
return -1
return result
BEST SOLUTION
This solution is O(N). Can someone explain the logic behind this solution.
def equi(A):
result = []
x=1
i=1
r=sum(A)
for e in A:
i-=1
r-=2*e
if -e==r:
result.append(-i)
return result