Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Python program to find Equilibrium index of an array

Python program to find Equilibrium index of an array

Equilibrium index of an array

Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes.

Sum of elements at lower indexes = Sum of elements at higher indexes.
Example

Arr= {-7,1,5,2,-4,3,0}

sum= -7+1+5=-1 -4+3+0=-1

Equilibrium Index= 3

Algorithm

  • Step 1- Initialize left_sum = 0
  • Step 2- Find the sum of the array as sum.
  • Step 3- For i = 1 to end of the array, do the following:
  • Step 4- Update sum to get the right sum.
  • step 5- sum = sum – arr[i] // sum is the right sum.
  • Step 6- If left_sum == sum, return current index.
  • Step 7- Update left_sum = left_sum + arr[i]
  • Step 8- Return -1 and exit the algorithm. // Equilibrium index is not found.

Python Program

a=list(map(int,input("ENTER ARRAY ELEMENTS ").split()))
ans=-1
for i in range(1,len(a)):
    if sum(a[:i])==sum(a[i+1:]):
        ans=i
        print("EQUILIBRIUM INDEX OF AN ARRAY: ")
        break    
print(ans)