Skip to content

Instantly share code, notes, and snippets.

@lamchau
Last active December 3, 2015 19:16
Show Gist options
  • Save lamchau/69e0ea2cd23f242d2c4a to your computer and use it in GitHub Desktop.
Save lamchau/69e0ea2cd23f242d2c4a to your computer and use it in GitHub Desktop.
function findBalancePoint(array) {
if (array.length === 0) {
return 0;
}
if (array.length === 1) {
return 1;
}
// initial sums
var left = 0;
var right = 0;
// squeeze array
for (var i = 0, j = array.length - 1; i < j;) {
if (left < right) {
left += array[i++];
} else if (left > right) {
right += array[j--];
} else {
left += array[i++];
right += array[j--];
}
}
return left === right ? 1 : 0;
}
function test(array, expected) {
var result = findBalancePoint(array);
console.log(result === expected ? 'ok:' : 'failed:', array);
}
test([-1, 4, 3, 3], 1);
test([1, 2, 3, 3], 1);
test([], 0);
test([1], 1);
test([1, 2], 0);
test([2, 2], 1);
test([2, 4, 4, 2], 1);
test([0, 0, 0, 1, 1, 1], 1);
test([0, 0, 0, 1, 1, 5], 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment