Easyprefix-sum
Find Pivot Index
Problem (restated)
Return the leftmost pivot index where sum of left elements equals sum of right elements, or -1.
Intuition
Total sum is fixed; as you walk, leftSum grows and rightSum = total, leftSum, nums[i].
Approaches
Running left sum
Tested onlyTime O(n)Space O(1)
Idea. Compute total. For each i, if leftSum == total, leftSum, nums[i], return i. Else leftSum += nums[i].
Walkthrough. [1,7,3,6,5,6] → pivot at index 3 (1+7+3 = 5+6).
Trade-offs. Prefix arrays use O(n) space; running sum is enough.
Solution
export function pivotIndex(nums: number[]): number {
const total = nums.reduce((a, b) => a + b, 0);
let left = 0;
for (let i = 0; i < nums.length; i++) {
if (left === total - left - nums[i]!) return i;
left += nums[i]!;
}
return -1;
}
export function pivotIndex(nums: number[]): number {
const total = nums.reduce((a, b) => a + b, 0);
let left = 0;
for (let i = 0; i < nums.length; i++) {
if (left === total - left - nums[i]!) return i;
left += nums[i]!;
}
return -1;
}
Reflection
- Which cue made you pick this pattern in under 90 seconds?
- What input would break a wrong invariant?