Equilibrium Point


Tue Feb 08 2022 05:40:29 GMT+0000 (Coordinated Universal Time)

Saved by @Uttam #java #gfg #geeksforgeeks #arrays #practice #equilibriumpoint

class Solution {
    // Function to find equilibrium point in the array.
    public static int equilibriumPoint(long a[], int n) {

        //We store the sum of all array elements.
        long sum = 0;
        for (int i = 0; i < n; i++) 
           sum += a[i];

        //sum2 is used to store prefix sum.
        long sum2 = 0;
        int ans = -1;

        for (int i = 0; i < n; i++) {
            //Leaving out the value of current element from suffix sum.
            sum = sum - a[i];
            //Checking if suffix and prefix sums are same.
            if (sum2 == sum) {
                //returning the index or equilibrium point.
                return (i + 1);
            //Adding the value of current element to prefix sum.
            sum2 = sum2 + a[i];
        return -1;

Equilibrium Point Given an array A of n positive numbers. The task is to find the first Equilibium Point in the array. 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. Example 1: Input: n = 5 A[] = {1,3,5,2,2} Output: 3 Explanation: For second test case equilibrium point is at position 3 as elements before it (1+3) = elements after it (2+2). Example 2: Input: n = 1 A[] = {1} Output: 1 Explanation: Since its the only element hence its the only equilibrium point. Your Task: The task is to complete the function equilibriumPoint() which takes the array and n as input parameters and returns the point of equilibrium. Return -1 if no such point exists. Expected Time Complexity: O(n) Expected Auxiliary Space: O(1) Constraints: 1 <= n <= 10^6 1 <= A[i] <= 10^8