So in an attempt to solve the above problem (Link from codewars, https://www.codewars.com/kata/5679aa472b8f57fb8c000047/javascript) I came up with the below solution in pseudocode (which didnt work)
- Declare two variables mid and i mid= we will assume this is the index we are looking for i= this is starting index
- Then while (mid<= arr.length-1) we will go through the array and add up each side of the array one side from i=0 to i=mid and then from i=mid to i=array.length-1, while adding up each side to leftSum and rightSum respectively
- And if leftSum==rightSum in any of these instances we will return mid if it didnt it will increase mid by one and reiterate ,
- If mid is not returned we will return -1 at the end.
More details about this is here https://stackoverflow.com/questions/71543463/equal-sides-of-an-array-in-js
Now below algorithm/solution is the correct answer for this question
- Find the sum of all the integers and assign it to a variable 'right'
- Then assign a variable named 'left' to 0
- Basically iterate through each element and do the following
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;
}
- Finally if none of the conditions above are met return-1
So the final solution 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;
}
Here are some questions you might wanna ask yourself
1) Why did we write if i>0 in
in the first line in the for loop
2) Why did we write i-1 in the line 'left = left + arr[i-1]'
Leave your answers in the comments below :)
Top comments (0)