Find Pivot Index in Python

Locate the index where the sum of elements to the left equals the sum to the right, using a single pass with prefix sums.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

20 lines
Python 3.9+
def find_pivot_index(nums):
    total = sum(nums)
    left_sum = 0
    for i, num in enumerate(nums):
        if left_sum == total - left_sum - num:
            return i
        left_sum += num
    return -1


if __name__ == "__main__":
    test_cases = [
        [1, 7, 3, 6, 5, 6],
        [1, 2, 3],
        [2, 1, -1],
        [0, 0, 0, 0],
        [-1, -1, -1, -1, -1, 0]
    ]
    for arr in test_cases:
        print(f"{arr} -> pivot index: {find_pivot_index(arr)}")

Output

stdout
[1, 7, 3, 6, 5, 6] -> pivot index: 3
[1, 2, 3] -> pivot index: -1
[2, 1, -1] -> pivot index: 0
[0, 0, 0, 0] -> pivot index: 0
[-1, -1, -1, -1, -1, 0] -> pivot index: 2

How it works

The algorithm computes the total sum once, then iterates while maintaining a running left_sum. At each index, the right sum is derived as total - left_sum - nums[i], avoiding repeated summation. The pivot condition left_sum == right_sum is checked before updating left_sum, so index 0 works when the whole array sums to zero or the left is empty. This yields an O(n) time and O(1) space solution, using enumerate to pair each value with its index. The early return ensures the first valid pivot is returned, matching typical problem requirements.

Common mistakes

  • Forgetting to check the condition before updating left_sum, causing off-by-one errors
  • Returning -1 without exhausting all elements, especially when the array has negative numbers
  • Computing the total sum repeatedly inside the loop, making the solution O(n^2)

Variations

  1. Use a prefix sum array to precompute sums, then scan with index lookups
  2. Use a two-pointer approach from both ends when the array is sorted (though not general)

Real-world use cases

  • Determining a split point in a dataset where cumulative features on both sides are balanced for load distribution.
  • Finding the optimal position to partition a time series for training and validation splits based on sum of metrics.
  • Locating a breakpoint in financial transaction logs where cumulative debits equal cumulative credits.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.