-
Notifications
You must be signed in to change notification settings - Fork 0
/
findEvenIndex.js
17 lines (14 loc) · 760 Bytes
/
findEvenIndex.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1.
// For example:
// Let's say you are given the array {1,2,3,4,3,2,1}:
// Your function will return the index 3, because at the 3rd position of the array, the sum of left side of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6.
function findEvenIndex(arr) {
let left = 0;
let right = arr.reduce((s, n) => s + n, 0);
for (let i = 0; i < arr.length; i++) {
right -= arr[i];
if (left === right) return i;
left += arr[i];
}
return -1;
}