Linear & Sentinel Search

Find Pivot Index

Easy
Solve it on LeetCode ↗

The problem

Return the leftmost index where the sum of elements strictly to the left equals the sum strictly to the right, or −1.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Compute the total sum once.
  2. 2Scan left to right with a running leftSum.
  3. 3At each i: if leftSum === total − leftSum − nums[i], return i.
  4. 4Otherwise add nums[i] to leftSum. Return −1 after the loop.

Key insight

Maintaining one running aggregate while deriving its complement from the total is the standard way to collapse two-sided scans into one pass.

The solution

Watch out for

  • Index 0 can be the answer (empty left side sums to 0) — check BEFORE adding nums[i].
  • Negative numbers are allowed; do not assume sums grow monotonically.