linkjobai

Find Pivot Index (LeetCode 724): Prefix Sums Without the Prefix Array

The pivot index is the position where the sum of everything to its left equals the sum of everything to its right. Return the leftmost one, or -1. It is a short problem that shows whether you can turn a prefix-sum idea into constant extra space.

The identity that does the work

Let total be the sum of the array and left the sum of elements before index i. The right side is then total - left - nums[i]. Index i is a pivot exactly when left == total - left - nums[i], which rearranges to 2 * left + nums[i] == total.

One pass, O(1) space

def pivot_index(nums):
    total = sum(nums)
    left = 0
    for i, x in enumerate(nums):
        if 2 * left + x == total:
            return i
        left += x
    return -1

Update left after the check, not before, because the pivot itself belongs to neither side. That ordering is the single most common bug.

Edge cases to say out loud

  • Index 0 can be a pivot: the left sum is 0 by definition, so [2, 1, -1] returns 0.
  • Negative numbers are allowed, so you cannot stop early when sums "overshoot". The scan must be complete.
  • An empty array returns -1.

Follow-ups

  • Return all pivot indices: collect instead of returning on the first hit.
  • Find the Middle Index in Array (LeetCode 1991) is the same problem with a different name, which is a nice thing to recognise.
  • Product versions use the same left/right decomposition, as in Product of Array Except Self.

Disclosure: I work on Linkjob AI. We build an AI assistant for technical interviews if you want real-time help practising rounds like this.