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.
I have written the following
- Declare two variables mid and i where
mid 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.
In code it is the following
function findEvenIndex(arr)
{
//Code goes here!
let mid =1;
let leftSum=0;
let rightSum=0;
while(mid<(arr.length-1)){
for(i=0;i<mid;i++){
leftSum=leftSum+arr[i]
}
rightSum = rightSum + arr[mid]
if(rightSum==leftSum){
console.log("mid: "+ mid);
return mid;
}
else{
mid++;
}
}
return -1;
}
however I am not sure why this is not working, any help would be appreciated