Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find index whose left and right elements sums are equal in Python
Suppose we have a list of numbers called nums, we have to find the smallest index i such that the sum of the numbers which are present at the left of i is equal to the sum of numbers present at right of i. If we cannot find any such solution, return -1.
So, if the input is like nums = [8,2,3,6,5,2,5,9,1,2], then the output will be 4, because sum of elements that are left of index 4 is [8,2,3,6] = 19, and sum of elements that are present at right is [2,5,9,1,2] = 19 also.
Algorithm
To solve this, we will follow these steps −
r := sum of all elements present in nums
l := 0
-
for each index i and value x in nums, do
r := r - x
-
if r is same as l, then
return i
l := l + x
return -1
Example
Let us see the following implementation to get better understanding −
def solve(nums):
r = sum(nums)
l = 0
for i, x in enumerate(nums):
r -= x
if r == l:
return i
l += x
return -1
nums = [8, 2, 3, 6, 5, 2, 5, 9, 1, 2]
print(solve(nums))
The output of the above code is −
4
How It Works
The algorithm uses a two-pointer approach with running sums. Initially, the right sum contains all elements, and the left sum is zero. As we iterate through each element, we subtract it from the right sum and check if both sums are equal. If they match, we found our index. Otherwise, we add the current element to the left sum and continue.
Edge Cases
Let's test with an array where no equilibrium index exists −
def solve(nums):
r = sum(nums)
l = 0
for i, x in enumerate(nums):
r -= x
if r == l:
return i
l += x
return -1
# Test case with no equilibrium
nums = [1, 2, 3, 4]
print(solve(nums))
-1
Conclusion
This approach efficiently finds the equilibrium index in O(n) time complexity using two running sums. The algorithm handles both cases where an equilibrium exists and where none exists, returning the appropriate index or -1.
