Given an integer array nums, count the number of valid splits at index i where the sum of nums[0..i] is greater than or equal to the sum of nums[i+1..n-1], and there is at least one element on each side.
Engineering takeaway. The "two sums" in this problem are secretly one sum: the total. Once you compute
total, the right half is justtotal - left. This is the same collapse we use in real systems whenever we replace a scan with a running aggregate — a rolling total is the cheapest data structure you'll ever maintain.
Intuition
Two values change as the split point moves forward: leftSum (the left half) and rightSum (the right half). But they're not independent — no matter where you split, leftSum + rightSum always equals the total sum of the array.
So the real question becomes: how do we update leftSum cheaply as i advances, and derive rightSum without a second scan?
Approach
- Compute
totalSumonce. - Sweep
ifrom0ton - 2:leftSum += nums[i]rightSum = totalSum - leftSum- if
leftSum >= rightSum, count the split.
function waysToSplitArray(nums: number[]): number {
const totalSum = nums.reduce((sum, num) => sum + num, 0);
let leftSum = 0;
let result = 0;
for (let i = 0; i < nums.length - 1; i++) {
leftSum += nums[i];
const rightSum = totalSum - leftSum;
if (leftSum >= rightSum) {
result++;
}
}
return result;
}Complexity
- Time:
O(n)— one pass after the initialreduce. - Space:
O(1)— a handful of numbers.
The lesson
When a problem hands you two quantities that always add to a constant, compute the constant and derive one quantity from the other. You'll often turn an O(n²) double-scan into a clean single pass.