Coders Packet

Equilibrium Point in C++

By Saravanan.V

In this tutorial, we are going to learn how to find the equilibrium point in the given array in C++.

Equilibrium Point in C++

In a given array, we have to find the equilibrium point and print the element and its position as the output. An 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.

Approach:

First, let's consider an array

arr={1,3,5,2,2}

Here the equilibrium element is 5 because arr[0]+arr[1]=4 and arr[3]+arr[4]=4. The approach is to get the total sum of the elements and then initialize a new temp sum to zero. Iterate through the loop by keeping updating temp sum and subtract the total sum by that element. When the total sum and temp sum are equal, that's the equilibrium point.

Pseudocode:

1.Calculate the total sum of the elements.
2.Initialize the temp sum as 0.
3.Iterate through the loop.
4.Add the element to temp sum.
5.Check the temp sum and total sum are equal, if it is print that element and its position.
6.Subtract the total sum by that element. 

Code in C++:

#include <bits/stdc++.h>
using namespace std;
int main()
{
     int n=5,a[n]={1,3,5,2,2},total_sum=0,temp_sum=0,i;
     if(n==1)//If only one element is present, then 1 is the equilibrium point and that element is equilibrium element
        cout<<"Equilibrium Point : "<<1<<"\nEquilibrium Element :"<<a[0]<<endl;
     for(i=0;i<n;i++)
        total_sum+=a[i];
     for(i=0;i<n;i++)
         {
          temp_sum=temp_sum+a[i];
           if(temp_sum==total_sum)
            cout<<"Equilibrium Point : "<<i+1<<"\nEquilibrium Element : "<<a[i]<<"\n";
total_sum=total_sum-a[i];
}
}

Output:

Equilibrium Point : 3
Equilibrium Element : 5

Time Complexity: O(n)
Space Complexity: O(1)

 

Download Complete Code

Comments

No comments yet