InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Find Pivot Index

easy Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug