LeetCode: Find Pivot Index
Find the pivot index in an array where the sum of the numbers to the left is equal to the sum of the numbers to the right.
See original problem on leetcode.com
Difficulty: Easy
Solution
The pivot index is the index where the sum of all the numbers to the left of the index is equal to the sum of all the numbers to the right of the index.
For every index i, total_sum = left_sum + nums[i] + right_sum.
Runtime
4 ms | Beats 73.33%
class Solution: def pivotIndex(self, nums: List[int]) -> int: n = len(nums)
total_sum = sum(nums)
left_sum = 0 for i in range(n): if left_sum == (total_sum - nums[i] - left_sum): return i
left_sum += nums[i]
return -1