Find Pivot Index - Problem

Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the right of the index.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

Input & Output

Example 1 — Basic Pivot Found
$ Input: nums = [1,7,3,6,5,6]
Output: 3
💡 Note: At index 3: left sum = 1+7+3 = 11, right sum = 5+6 = 11. Both sums are equal, so pivot index is 3.
Example 2 — No Pivot Exists
$ Input: nums = [1,2,3]
Output: -1
💡 Note: No index where left sum equals right sum. Index 0: left=0, right=5. Index 1: left=1, right=3. Index 2: left=3, right=0.
Example 3 — Pivot at Edge
$ Input: nums = [2,1,-1]
Output: 0
💡 Note: At index 0: left sum = 0 (no elements), right sum = 1+(-1) = 0. Both are equal, so pivot is at index 0.

Constraints

  • 1 ≤ nums.length ≤ 104
  • -1000 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Find Pivot Index INPUT Array: nums 1 i=0 7 i=1 3 i=2 6 i=3 5 i=4 6 i=5 At pivot index 3: Left: 1+7+3 Right: 5+6 = 11 = 11 = Input Values nums = [1,7,3,6,5,6] length = 6 total_sum = 28 ALGORITHM STEPS 1 Calculate Total Sum total = 1+7+3+6+5+6 = 28 2 Initialize left_sum = 0 Start with empty left side 3 Iterate Through Array Check each index as pivot 4 Check Condition left_sum == total - left - nums[i] Iteration Details i left right match? 0 0 27 NO 1 1 20 NO 2 8 17 NO 3 11 11 OK! Found at i=3: left==right FINAL RESULT Pivot Index Found! 1 7 3 6 5 6 PIVOT Left side (sum=11) Pivot (index=3) Right side (sum=11) Output 3 Pivot index where left_sum == right_sum Key Insight: Instead of calculating left and right sums separately for each index (O(n^2)), we use a single pass approach: right_sum = total_sum - left_sum - nums[i]. If left_sum equals right_sum, we found our pivot! Time Complexity: O(n) | Space Complexity: O(1) TutorialsPoint - Find Pivot Index | Optimal Solution (Prefix Sum)
Asked in
Facebook 35 Amazon 28 Microsoft 22
85.0K Views
Medium Frequency
~15 min Avg. Time
2.5K 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