
Question: You have given an array of integer. You need to create the algorithm which finds the balance point in the given array and return index of that point.
Read More About Interview Questions and Answers for Software Engineer
Example:
Input: [1,2,2,9,3,2]
Output: 3
Solution: To solve this problem, we need to find the point from which sum of the left side of array and sum of the right side of array would be exact same.
In given example “9” is the balance point. So sum of left side elements === 1+ 2+ 2 = 5 and sum of right side elements === 3 + 2 = 5. Both are exact same.
Now we can solve this challenge by traversing through array and comparing the left side array and right side array. For example
we can define sum = addition of total elements = 19
we can define leftsum = 0
Now on first element we can do 19 – 1 = 18
check if leftsum === sum ? return i if it is true
otherwise leftsum = 0 + 1 = 1
return false if we couldn’t find the balance point
Keep doing same for all elements in the array.
Here is the Working Solution:
const sumPoint = (arr) => {
const len = arr.length;
let sum = 0;
let leftsum = 0;
for (let i = 0; i < len; i++) {
sum += arr[i];
}
for (let j = 0; j < len; j++) {
sum -= arr[j];
if (leftsum === sum) {
return j;
}
leftsum += arr[j];
}
return false;
}
const arr = [1,2,2,9,3,2];
console.log(sumPoint(arr));
Play Code Here:
Leave a Reply