Time Complexity: .
Solution 1
The pivot index must have the same sum on its left and its right. To calculate this, we can create a prefix sum of the array (in my solution it is cushioned with one at index ). Loop through every index in the array and check whether
If this is true, we can return our current index because the problem wants the left-most index. If it finishes the for-loop without returning, it means there is no valid pivot index so return .
Implementation
from typing import Listclass Solution:def pivotIndex(self, nums: list[int]) -> int:psums = [0]for i in range(len(nums)):# Notice i in psums is always one less than the current indexpsums.append(psums[i] + nums[i])
Solution 2
The alternate solution does not require an array to store the sums. Instead, we only need the total sum of the array and the current sum at each index (exclusive of index). With this we check whether
Note: This is technically the same solution as solution 1, but it is another way to think about approaching this question.
Implementation
from typing import Listclass Solution:def pivotIndex(self, nums: List[int]) -> int:total = sum(nums)curSum = 0for i in range(len(nums)):# curSum is up to i not inclusive of i.if curSum == total - curSum - nums[i]:return i# updating curSumcurSum += nums[i]return -1
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!