SDE & MLE Prep

724. Find Pivot Index

Problem

Return the leftmost index where the sum of the elements strictly to its left equals the sum of the elements strictly to its right (an empty side sums to 0), or −1 if there is none.

Example: [1,7,3,6,5,6] → 3 (1 + 7 + 3 = 5 + 6); [1,2,3] → -1

Constraints: n ≤ 10⁴.

With total known, the right sum at i is total − left − nums[i]. Scan once, maintaining left; return the first i where both sides match.

Complexity: O(n) time, O(1) space.

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        total, left = sum(nums), 0
        for i, x in enumerate(nums):
            if left == total - left - x:
                return i
            left += x
        return -1