Find Pivot Index - Problem

Imagine you have an array of integers, and you need to find the perfect balance point - an index where the sum of all elements to its left equals the sum of all elements to its right.

Given an array nums, find the pivot index where:

  • The sum of elements strictly to the left equals the sum of elements strictly to the right
  • If the index is at the leftmost position, consider the left sum as 0
  • If the index is at the rightmost position, consider the right sum as 0

Goal: Return the leftmost pivot index, or -1 if no such index exists.

Example: For array [1, 7, 3, 6, 5, 6], index 3 is the pivot because left sum = 1+7+3 = 11 and right sum = 5+6 = 11.

Input & Output

example_1.py โ€” Basic Pivot
$ Input: [1, 7, 3, 6, 5, 6]
โ€บ Output: 3
๐Ÿ’ก Note: At index 3, left sum = 1+7+3 = 11 and right sum = 5+6 = 11. Both sides are equal.
example_2.py โ€” No Pivot
$ Input: [1, 2, 3]
โ€บ Output: -1
๐Ÿ’ก Note: No index exists where left and right sums are equal. Index 0: left=0, right=5. Index 1: left=1, right=3. Index 2: left=3, right=0.
example_3.py โ€” Edge Case
$ Input: [2, 1, -1]
โ€บ Output: 0
๐Ÿ’ก Note: At index 0, left sum = 0 (no elements to left) and right sum = 1 + (-1) = 0. Both sides equal 0.

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • -1000 โ‰ค nums[i] โ‰ค 1000
  • Note: Array can contain negative numbers and zeros

Visualization

Tap to expand
Finding the Perfect Seesaw Balance1+7+3=116PIVOT5+6=11Formula: Left Sum ร— 2 + Pivot = Total SumCheck: 11 ร— 2 + 6 = 28 โœ“Left: 11Right: 11Array: [1, 7, 3, 6, 5, 6] โ†’ Total: 28
Understanding the Visualization
1
Calculate Total Weight
First, we need to know the total weight of all elements: 1+7+3+6+5+6 = 28
2
Find Balance Point
We check each position to see if it can be our fulcrum. At each position, we know: Left Weight + Right Weight + Current Element = Total Weight
3
Apply Balance Formula
For balance: Left Weight = Right Weight. So: Left Weight ร— 2 + Current Element = Total Weight
4
Success!
At index 3: Left Weight (11) ร— 2 + Current (6) = 28 โœ“. Perfect balance achieved!
Key Takeaway
๐ŸŽฏ Key Insight: Instead of recalculating sums repeatedly, we use the mathematical relationship that at the pivot point: `leftSum ร— 2 + currentElement = totalSum`. This allows us to find the balance point in just one pass!
Asked in
Amazon 45 Microsoft 38 Google 32 Meta 28
48.9K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen