'2 questions about a solution Equal sides of an array
Question: Take an array with integers 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. Let's say you are given the array {1,2,3,4,3,2,1}: Your function equalsides() 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.
One working solution I found online is
function findEvenIndex(arr)
{
var left = 0, right = arr.reduce(function(pv, cv) { return pv + cv; }, 0);
for(var i = 0; i < arr.length; i++) {
if(i>0) {
left =left+ arr[i-1];
}
right =right- arr[i];
if(left == right)
return i;
}
return -1;
}
I am not able to explain the following two lines of code, any help would be appreciated!
- Why write
if i>0in in the first line in the for loop - Why write
i-1in the lineleft = left + arr[i-1]
Solution 1:[1]
Well the if(i>0) is required, because, arrays can't have negative indexes in JS. and i-1 is required, because, you want to add elements to the left of the balance position to the left item, not including the balance position. Though I do believe, this is a better solution:
function findEvenIndex(arr){
let left = 0, right = arr.reduce( (a,b) => (a+b), 0);
for(let i in arr){
right -= arr[i];
if(right == left) return i;
left += arr[i];
}
return -1;
}
Arguably it's the same code, but, this has only one if statement and is a bit more apparent. Hope this helped :-)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hiten Tandon |
