Problem of The Day: Find Pivot Index
Problem Statement
My Solution [Accepted]
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
prefix = []
curr_sum = 0
total_sum = sum(nums)
for i, num in enumerate(nums):
if total_sum - curr_sum - num == curr_sum:
return i
curr_sum += num
return -1
Editorial
Approach #1: Prefix Sum [Accepted]
class Solution(object):
def pivotIndex(self, nums):
S = sum(nums)
leftsum = 0
for i, x in enumerate(nums):
if leftsum == (S - leftsum - x):
return i
leftsum += x
return -1