Program to find index whose left and right elements sums are equal in Python


Suppose we have a list of items 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.

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))

Input

[8,2,3,6,5,2,5,9,1,2]

Output

4

Updated on: 11-Oct-2021

443 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements