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.
Python code
20 linesdef 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
[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
- Use a prefix sum array to precompute sums, then scan with index lookups
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.