Typorithm · easy

Find Pivot Index

pivot-indexprefix-sumsrunning-sumbalancetotal
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Find Pivot Index

0%

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.

01

Right = total - left - current.

02

Test before adding current to left.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Whole-array sum

Precompute the total to derive the right sum cheaply.

const total = nums.reduce((a, b) => a + b, 0)

2. Balance test

Right sum is total minus left sum minus the pivot itself.

if (leftSum === total - leftSum - nums[i])

3. Grow left

Extend the left sum after testing index i.

leftSum += nums[i]

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Find Pivot Index: Lesson & Practice · Typorithm | ApplyDjinn