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 thirds with equal sums in JavaScript
We are required to write a JavaScript function that takes in an array of integers as the first and the only argument. Our function should return true if and only if we can partition the array into three non-empty parts with equal sums, false otherwise.
Problem Statement
Given an array of integers, determine if it can be split into exactly three contiguous subarrays with equal sums.
For example, if the input to the function is:
const arr = [3, 3, 6, 5, -2, 2, 5, 1, -9, 4];
Then the output should be:
const output = true;
Output Explanation
The array can be partitioned as: [3, 3] | [6] | [5, -2, 2, 5, 1, -9, 4] where each part sums to 6:
3 + 3 = 6 6 = 6 5 - 2 + 2 + 5 + 1 - 9 + 4 = 6
Solution Approach
The algorithm works by:
- Calculating the total sum and checking if it's divisible by 3
- Finding the target sum for each part (total sum / 3)
- Iterating through the array to find three consecutive parts with the target sum
Example
const arr = [3, 3, 6, 5, -2, 2, 5, 1, -9, 4];
const thirdSum = (arr = []) => {
const sum = arr.reduce((acc, val) => acc + val, 0);
// Check if sum is divisible by 3
if (!Number.isInteger(sum / 3)) {
return false;
}
let count = 0;
let curr = 0;
const target = sum / 3;
for (const num of arr) {
curr += num;
if (curr === target) {
curr = 0;
count += 1;
}
}
return count === 3 && curr === 0;
};
console.log(thirdSum(arr));
true
Testing with Different Cases
// Test case 1: Valid partition console.log(thirdSum([0, 2, 1, -6, 6, 7, 9, -1, 2, 0, 1])); // Test case 2: Cannot be divided by 3 console.log(thirdSum([1, 2, 3, 4])); // Test case 3: All zeros console.log(thirdSum([0, 0, 0, 0]));
true false true
Key Points
- The total sum must be divisible by 3 for a valid partition to exist
- Each part must sum to exactly (total sum / 3)
- The algorithm finds three consecutive parts by tracking cumulative sums
- Time complexity: O(n), Space complexity: O(1)
Conclusion
This solution efficiently determines if an array can be partitioned into three equal-sum parts using a single pass through the array. The key insight is checking divisibility by 3 first, then tracking cumulative sums to find the partition points.
