Easy
Find Pivot Index
- Time limit
- 1 s
- Memory limit
- 256 MB
- Estimated
- 20 min
- Prefix Sums and Difference Arrays
Description
Description
Given an integer array nums, find the pivot index: the index where the sum of all numbers strictly to the left of the index equals the sum of all numbers strictly to the right of the index.
If the pivot index is at the edge of the array, the missing side has sum 0. If no such index exists, return -1.
Return the leftmost pivot index if multiple pivot indices exist.
Examples
Example 1
- Input:
nums = [1, 7, 3, 6, 5, 6] - Output:
3 - Explanation: At index
3, the left sum is1 + 7 + 3 = 11and the right sum is5 + 6 = 11.
Example 2
- Input:
nums = [1, 2, 3] - Output:
-1 - Explanation: No index has equal left and right sums.
Example 3
- Input:
nums = [2, 1, -1] - Output:
Constraints
1 <= nums.length <= 100000-1000 <= nums[i] <= 1000- The leftmost valid index must be returned.
Sample cases
3Sample 1
Input
nums = [1,7,3,6,5,6]
Expected output
3
Sample 2
Input
nums = [1,2,3]
Expected output
-1
Skills and languages
Concepts
- Prefix Sum Array
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer