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.
Function Signature
def pivot_index(nums: list[int]) -> int:
Rules
-
The element at the candidate index belongs to neither side.
-
An empty side sums to
0
. Index
0
is a pivot when the elements after it sum to
0
, and the last index is a pivot when the elements before it sum to
0
.
-
When several indices are pivots, return the smallest one. Return
-1
when there is none.
Constraints
-
1 <= len(nums) <= 10^4
-
-1000 <= nums[i] <= 1000
Examples
Input: nums = [1, 7, 3, 6, 5, 6]
Output: 3
The sum to the left of index 3 is 1 + 7 + 3 = 11 and the sum to its right is 5 + 6 = 11. Indices 0, 1 and 2 do not balance, so 3 is the leftmost pivot.
Input: nums = [1, 2, 3]
Output: -1
The (left, right) sums are (0, 5) at index 0, (1, 3) at index 1 and (3, 0) at index 2. None of them match.
Input: nums = [2, 1, -1]
Output: 0
Index 0 has nothing to its left, so its left sum is 0, and the elements to its right sum to 1 + (-1) = 0.