Created
September 18, 2015 09:02
-
-
Save jeanlescure/5ccad7ad0b50ef7561aa to your computer and use it in GitHub Desktop.
Codility Equi Solution in Javascript - 100% score
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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 < N and the sum of elements of lower indices is equal to the sum of elements of higher indices, i.e. | |
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. | |
*/ | |
function solution(A) { | |
var sum = A.reduce(function(pv, cv) { return pv + cv; }); | |
var sum_right; | |
var sum_left = 0; | |
for(i = 0; i < A.length; i++) { | |
sum_right = sum - sum_left - A[i]; | |
if (sum_left === sum_right) return i; | |
sum_left += A[i]; | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the codes, but it would fail when A is empty or a single number array, here is the correct answer: