Find the Equilibrium Index of a List in Python
Find every index in a list where the sum of elements to its left equals the sum to its right, using a single pass.
Python code
16 linesdef find_equilibrium_indexes(arr):
total = sum(arr)
left_sum = 0
indexes = []
for i, num in enumerate(arr):
total -= num
if left_sum == total:
indexes.append(i)
left_sum += num
return indexes
if __name__ == "__main__":
test = [1, 2, 3, -1, 2, 3]
result = find_equilibrium_indexes(test)
print("Array:", test)
print("Equilibrium indexes:", result)
Output
Array: [1, 2, 3, -1, 2, 3]
Equilibrium indexes: [3]
How it works
The algorithm starts with total being the sum of the whole list and left_sum as 0. On each iteration it subtracts the current number from total so total now represents the right-side sum, compares it to left_sum, and appends the index when they match. Then it adds the current number to left_sum before moving on. This keeps the time complexity at O(n) with O(1) extra space aside from the result list.
Common mistakes
- Forgetting that an empty list has no equilibrium indexes
- Treating the comparison before updating `left_sum`, which would produce incorrect results
- Assuming only one equilibrium index can exist when multiple are possible
Variations
- Use prefix sums to precompute left and right totals, then compare them at each index
- Use recursion to split the list and check the middle index recursively
Real-world use cases
- Analyzing CPU load balancing by finding the moment where accumulated task load equals the remaining load.
- Segmenting a revenue stream so that the total profit before a date equals the total after it, for tax or accounting reports.
- Splitting a dataset for training and prediction when you need an index that splits a cumulative metric in half.
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.