InterviewPrepKit

Home / Coding / Arrays & Hashing

Find Pivot Index

easy Original β†—
Solving tips
  • Repeated range-sum queries at many positions signal prefix sums: compute total once, then each side is O(1) arithmetic.
  • Sweep left to right with a running left sum; the right sum is total - left - nums[i], giving O(n) time and O(1) space.
  • The pivot element belongs to neither side, so the check is left == total - left - nums[i], and edges (empty left at index 0, empty right at last) are valid.
  • Compare before adding nums[i] to left, or you shift every check and miss the leftmost pivot; negatives make sums non-monotonic so no binary-search shortcut.

Problem

Given an integer array nums, find its pivot index: an index where the sum of all elements strictly to its left equals the sum of all elements strictly to its right. The element at the pivot itself belongs to neither side.

For the leftmost index, the left sum is 0; for the rightmost index, the right sum is 0. Return the leftmost pivot index, or -1 if none exists.

Examples

  • nums = [1,7,3,6,5,6] β†’ 3 β€” left of index 3: 1 + 7 + 3 = 11; right of it: 5 + 6 = 11.
  • nums = [1,2,3] β†’ -1 β€” no index balances (e.g. at index 0: left 0 vs right 5).
  • nums = [2,1,-1] β†’ 0 β€” left of index 0 is empty (0), and right is 1 + (-1) = 0.

Constraints

  • 1 <= len(nums) <= 10^4
  • -1000 <= nums[i] <= 1000

Recomputing both sums for every candidate index is O(n^2); the intended solution is a single O(n) pass.

Think about it first

Hint 1 For a fixed index i, what are the two sums you need? How expensive is computing them from scratch, and how many indices are there?
Hint 2 If you know the total sum of the array and the sum of everything left of i, can you get the right sum without another loop?
Hint 3 Compute `total = sum(nums)` once. Sweep i from left to right maintaining a running `left`; at each i the right sum is `total - left - nums[i]`. Return the first i where they match.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.