Find an index in an array such that its prefix sum equals its suffix sum.
A[0] + A[1] + ... + A[P−1] = A[P+1] + ... + A[N−2] + A[N−1].
A[0] = -7 A[1] = 1 A[2] = 5 A[3] = 2 A[4] = -4 A[5] = 3 A[6] = 0
P = 3 is an equilibrium index of this array, because:
- A[0] + A[1] + A[2] = A[4] + A[5] + A[6]
P = 6 is also an equilibrium index, because:
- A[0] + A[1] + A[2] + A[3] + A[4] + A[5] = 0
the function may return 3 or 6, as explained above.
Complexity:
- expected worst-case time complexity is O(N);
- expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
function solution($A) {
// write your code in PHP5
$sum=0;
for($i=0;$i<count($A);$i++){
$sum+=$A[$i];
}
$left=0;
for($i=0;$i<count($A);$i++){
if($left==$sum-$A[$i]-$left){
return $i;
}
$left+=$A[$i];
}
return -1;
}