Find Pivot Index
Description
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 index's right. The element at the pivot index is NOT included in either sum. 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.
Example 1:
Input: nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation: The pivot index is 3 (value = 6, but excluded from sums).
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11
Left sum == Right sum, so index 3 is the pivot.
Example 2:
Input: nums = [1, 2, 3]
Output: -1
Explanation: Check each index:
- Index 0: left = 0, right = 2 + 3 = 5. 0 != 5
- Index 1: left = 1, right = 3. 1 != 3
- Index 2: left = 1 + 2 = 3, right = 0. 3 != 0
No index satisfies left sum == right sum.
Example 3:
Input: nums = [2, 1, -1]
Output: 0
Explanation: The pivot index is 0. Left sum = 0 (no elements to the left). Right sum = 1 + (-1) = 0. Left sum == Right sum.
Constraints
1 <= nums.length <= 10^4-1000 <= nums[i] <= 1000
Complexity
Show Complexity
- Time:
O(n) - Space:
O(1)
Hints
Show Hints
- Pattern
- Prefix sum
- Approach
- Compute total sum. Iterate through array: at each index, right_sum = total - left_sum - nums[i]. If left_sum == right_sum, return index. Update left_sum += nums[i].
- Complexity
- Calculate total sum first, then iterate tracking left sum
Solutions
Show PY Solution
def solution(nums):
if len(nums) == 1:
return 0
sums = 0
for i in range(len(nums)):
sums += nums[i]
left_sum = 0
for i in range(len(nums)):
if left_sum == (sums - left_sum - nums[i]):
return i
left_sum += nums[i]
return -1