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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code