Find Pivot Index
EasyPrefix Sum · NVIDIA
You are given an integer array nums. An index i is a pivot index when the sum of the elements strictly to the left of i equals the sum of the elements strictly to the right of i. The element nums[i] itself is not counted on either side.
- At
i = 0there is nothing on the left, so the left sum is0. - At the last index there is nothing on the right, so the right sum is
0.
Return the smallest pivot index. If no index is a pivot, return -1.
Values can be negative, so the sums do not necessarily grow as you move right.
Example 1
- Input:
- nums = [2, 3, -1, 8, 4]
- Output:
- 3
- Explanation
- At index 3 the left side is 2 + 3 + (-1) = 4 and the right side is just 4. No earlier index balances (for example, index 2 has 5 on the left and 12 on the right), so the answer is 3.
Example 2
- Input:
- nums = [-1, -1, -1, 0, 1, 1]
- Output:
- 0
- Explanation
- At index 0 the left side is empty (sum 0) and the right side is -1 - 1 + 0 + 1 + 1 = 0. Index 0 already works, and it is the smallest possible answer.
Example 3
- Input:
- nums = [3, 1, 2]
- Output:
- -1
- Explanation
- Index 0 compares 0 with 3, index 1 compares 3 with 2, and index 2 compares 4 with 0. No index balances, so the answer is -1.
Constraints
- 1 ≤
nums.length≤ 104 - -1000 ≤
nums[i]≤ 1000