Equilibrium Point in the Array

0

 


Equilibrium point of an array is a point when the left sum is equal to the right sum . 

Input : -1 , 8  , 4 , 9 , -2

Output : 4

Because the left sum of 4 is (-1+8) which is 7 and the right sum is (9-2) which is again 7 . Both the sides are perfectly balanced hence it is an equilibrium point . 


Input : 3 , 4 , 8 , -9 , 20 , 6

Output : 20  (Here 3+4+8-9 is equal to 6 , hence 20  is the equilibrium point ).


Here we have 2 codes . One is in Java and the second one is in C++ .


Java Code :



public class ArrayE
{
    public static int equilibrium(int[] arr)
    {
        int sum=0;
        int check_sum=0;
        int left_sum=arr[0];
        for(int i=0;i<arr.length;i++)
        {
            sum+=arr[i];
        }
        for(int i=1;i<arr.length;i++)
        {
            if(sum-left_sum==check_sum)
                return arr[i-1];
            else{
                check_sum+=arr[i-1];
                left_sum+=arr[i];
            }
        }
        return -1;
    }

    public static void main(String [] args)
    {
        
        int [] arr ={-1,8,4,9,-2};
        System.out.print(equilibrium(arr));

    }
}



C++ Code :


public class ArrayE
{
    
    public static int equilibrium(int[] arr)
    {
        int length = sizeof(arr)/sizeof(arr[0]);
        int sum=0;
        int check_sum=0;
        int left_sum=arr[0];
        for(int i=0;i<length;i++)
        {
            sum+=arr[i];
        }
        for(int i=1;i<length;i++)
        {
            if(sum-left_sum==check_sum)
                return arr[i-1];
            else{
                check_sum+=arr[i-1];
                left_sum+=arr[i];
            }
        }
        return -1;
    }

    int main()
    {

        int [] arr ={-1,8,4,9,-2};
        
        cout<<equilibrium(arr);

    }  
}


Time Complexity : O(n)

Space Complexity : O(1)




Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !