1. Whole-array sum
Precompute the total to derive the right sum cheaply.
const total = nums.reduce((a, b) => a + b, 0)Typorithm · easy
Step 1 of 8 · intro card
Prefix Sums
Keep a running left sum; the pivot is where left equals (total - left - current), derived without a second array.
The pivot index has equal sums to its left and right.
Precompute the total, then sweep keeping a running left sum.
The right sum is total - leftSum - nums[i], so the balance check needs no extra array.
Right = total - left - current.
Test before adding current to left.
Return the first balanced index.
function pivotIndex(nums) {
const total = nums.reduce((a, b) => a + b, 0);
let leftSum = 0;
for (let i = 0; i < nums.length; i += 1) {
if (leftSum === total - leftSum - nums[i]) {
return i;
}
leftSum += nums[i];
}
return -1;
}Connect each part of the code to the concept before you type.
Precompute the total to derive the right sum cheaply.
const total = nums.reduce((a, b) => a + b, 0)Right sum is total minus left sum minus the pivot itself.
if (leftSum === total - leftSum - nums[i])Extend the left sum after testing index i.
leftSum += nums[i]Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.