Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Array index to balance sums in JavaScript
Finding a balance point in an array means locating an index where the sum of elements on the left equals the sum of elements on the right. This is a common array manipulation problem in JavaScript.
Problem Statement
We need to write a JavaScript function that takes an array of integers and returns the index where the left sum equals the right sum. If no such index exists, return -1.
For example, with the array [1, 2, 3, 4, 3, 2, 1], index 3 is the balance point because:
- Left side (indices 0-2): 1 + 2 + 3 = 6
- Right side (indices 4-6): 3 + 2 + 1 = 6
Method 1: Using Array.slice() and reduce()
This approach slices the array at each index and calculates sums using the reduce method:
const arr = [1, 2, 3, 4, 3, 2, 1];
const balancingIndex = (arr = []) => {
const findSum = arr => arr.reduce((acc, x) => acc + x, 0);
for (let i = 0; i < arr.length; i++) {
const leftSum = findSum(arr.slice(0, i));
const rightSum = findSum(arr.slice(i + 1));
if (leftSum === rightSum) {
return i;
}
}
return -1;
};
console.log(balancingIndex(arr));
console.log(balancingIndex([1, 2, 3])); // No balance point
console.log(balancingIndex([1])); // Single element
3 -1 0
Method 2: Optimized Single Pass Solution
A more efficient approach calculates the total sum once, then uses a running sum to check balance points:
const optimizedBalancingIndex = (arr = []) => {
if (arr.length === 0) return -1;
const totalSum = arr.reduce((sum, num) => sum + num, 0);
let leftSum = 0;
for (let i = 0; i < arr.length; i++) {
// Right sum = total - left - current element
const rightSum = totalSum - leftSum - arr[i];
if (leftSum === rightSum) {
return i;
}
leftSum += arr[i];
}
return -1;
};
const testArray = [1, 2, 3, 4, 3, 2, 1];
console.log(optimizedBalancingIndex(testArray));
console.log(optimizedBalancingIndex([2, 1, 6, 4])); // Index 2: left=3, right=4? No. Index 1: left=2, right=10? No.
console.log(optimizedBalancingIndex([-1, 0, 1])); // Index 1: left=-1, right=1? No. Actually index 1: left=-1, right=1
3 -1 1
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Array.slice() + reduce() | O(n²) | O(n) | High |
| Single Pass | O(n) | O(1) | Medium |
Edge Cases
// Test edge cases
console.log("Empty array:", balancingIndex([]));
console.log("Single element:", balancingIndex([5]));
console.log("Two elements:", balancingIndex([1, 1]));
console.log("All zeros:", balancingIndex([0, 0, 0]));
Empty array: -1 Single element: 0 Two elements: -1 All zeros: 0
Conclusion
The balance point problem can be solved with array slicing for simplicity or optimized with a single-pass algorithm for better performance. The optimized version is recommended for larger arrays due to its O(n) time complexity.
