- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- Related Questions & Answers
- Find maximum difference between nearest left and right smaller elements in Python
- Picking all elements whose value is equal to index in JavaScript
- Python – Check if elements index are equal for list elements
- Program to find maximum sum of two sets where sums are equal in C++
- Find maximum difference between nearest left and right smaller elements in C++
- Python – Check if elements in a specific index are equal for list elements
- Find largest subtree having identical left and right subtrees in Python
- Program to find k sublists with largest sums and return sums in ascending order in Python
- Program to print right and left arrow patterns in C
- Program to sqeeze list elements from left or right to make it single element in Python
- How to handle right-to-left and left-to-right swipe gestures on Android?
- Program to find valid matrix given row and column sums in Python
- Swap Even Index Elements And Odd Index Elements in Python
- How to handle right-to-left and left-to-right swipe gestures on iOS App?
- Program to find a tree by updating values with left and right subtree sum with itself in Python

Advertisements