Logo

Kode$word

Equilibrium Point

Equilibrium Point

GeeksForGeeks question based on prefix sum.

15 views
0
0

GeeksforGeeks Problem

Link of the Problem to try -: Link


Given an array of integers arr[], the task is to find the first equilibrium point in the array.

The equilibrium point in an array is an index (0-based indexing) such that the sum of all elements before that index is the same as the sum of elements after it. Return -1 if no such point exists.

Examples:

Input: arr[] = [1, 2, 0, 3]
Output: 2
Explanation: The sum of left of index 2 is 1 + 2 = 3 and sum on right of index 2 is 3.

Input: arr[] = [1, 1, 1, 1]
Output: -1
Explanation: There is no equilibrium index in the array.

Input: arr[] = [-7, 1, 5, 2, -4, 3, 0]
Output: 3
Explanation: The sum of left of index 3 is -7 + 1 + 5 = -1 and sum on right of index 3 is -4 + 3 + 0 = -1.

Constraints:

3 <= arr.size() <= 105

-104 <= arr[i] <= 104


Solution:

Solving the Equilibrium Index Problem

The core logic of this problem is finding the Prefix Sum and Suffix Sum. The goal is to identify the specific index where the sum of elements on the left equals the sum of elements on the right.

For beginners, this problem can feel difficult because it isn't immediately obvious how to "balance" the two sides of an array. Understanding these two concepts makes the solution simple:

  1. Prefix Sum: The cumulative sum of elements from left to right. We store the total sum at each index as we move forward.
  2. Suffix Sum: The cumulative sum of elements from right to left. We store the total sum at each index as we move backward.

By comparing these two sums, you can easily find the Equilibrium Point where the two halves of the array are equal.


Code:

class Solution {
// Function to find equilibrium point in the array.
public static int findEquilibrium(int arr[]) {
// code here
int prefix[] = new int[arr.length];
int suffix[] = new int[arr.length];

int presum=0;
for(int i=0;i<arr.length;i++){
presum+=arr[i];
prefix[i] = presum;
}

int suffsum=0;
for(int i=arr.length-1;i>=0;i--){
suffsum+=arr[i];
suffix[i] = suffsum;
}
for(int i=0;i<suffix.length;i++){
if(suffix[i] == prefix[i]){
return i;
}
}
return -1;

}
}