File: find-pivot-index/solution.py

Date: 2026-06-06

Time: 16:40

Purpose

This file implements the solution to LeetCode 724 - Find Pivot Index. It finds the leftmost index in an array where the sum of elements to the left equals the sum of elements to the right. The pivot element itself is excluded from both sums.

Key Components

Solution.pivotIndex(nums: List[int]) -> int — The sole method. Takes an integer array and returns the leftmost pivot index, or -1 if no pivot exists.

Patterns

Prefix sum with running accumulator. Rather than computing left and right sums from scratch at each index (which would be O(n^2)), the solution precomputes total = sum(nums) once, then maintains a running left_sum. At each index i, the right sum is derived algebraically:


right_sum = total - left_sum - nums[i]

This avoids a second pass or auxiliary array. The check leftsum == total - leftsum - num is equivalent to leftsum == rightsum. After checking, left_sum is updated by adding num — the order matters because the pivot element must be excluded from both sides.

This is the canonical single-pass prefix sum pattern: O(n) time, O(1) space.

Dependencies

Imports: Only typing.List for the type annotation — no external or project dependencies.

Imported by: The find-pivot-index/test_solution.py file. The massive "Imported By" list in the prompt is an artifact of shared test infrastructure across the repo, not direct consumers of this solution.

Flow

1. Compute total — the sum of all elements.

2. Initialize left_sum = 0.

3. Iterate with enumerate(nums):

4. If the loop completes without returning, return -1.

Invariants

Error Handling

None. The method assumes a valid list of integers per LeetCode constraints. It returns -1 as the sentinel for "no pivot found" — the standard LeetCode convention. An empty list would simply skip the loop and return -1.

Topics to Explore

Beliefs