Equilibrium Point in Array

Given an array A of N positive numbers. The task is to find the first Equilibrium Point in the array.
The equilibrium point in an array is a position such that the sum of elements before it is equal to the sum of elements after it.

Let say our array is like this A[0,1,…i-1,i,i+1,….N-1]

We can say element A[i] is Equilibrium if and only if sum of A[0,1,..i-1] is equal to sum of A[i+1,…,N-1].

So have you got an idea? I know you are thinking that for each element we will find sum before that element and sum after that element. But it takes O(n²) time and we need to solve our problem in O(n) time.

So we will find sum of all elements of the array then we traverse our array from left to right. To get right sum we will subtract the current element from totalsum. And while we traversing from left to right we also add current element to leftsum to find leftsum and we compare both if we find equal then return otherwise if we not find any pair then return -1.

Thanks for reading!!.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KuldipMochi

KuldipMochi

Software Engineer who loves to share ideas write poems