Java Program for Equilibrium index of an array
Last Updated :
14 Jan, 2022
Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in an array A:
Example :
Input: A[] = {-7, 1, 5, 2, -4, 3, 0}
Output: 3
3 is an equilibrium index, because:
A[0] + A[1] + A[2] = A[4] + A[5] + A[6]
Input: A[] = {1, 2, 3}
Output: -1
Write a function int equilibrium(int[] arr, int n); that given a sequence arr[] of size n, returns an equilibrium index (if any) or -1 if no equilibrium indexes exist.
Method 1 (Simple but inefficient)
Use two loops. Outer loop iterates through all the element and inner loop finds out whether the current index picked by the outer loop is equilibrium index or not. Time complexity of this solution is O(n^2).
Java
// Java program to find equilibrium
// index of an array
class EquilibriumIndex {
int equilibrium(int arr[], int n)
{
int i, j;
int leftsum, rightsum;
/* Check for indexes one by one until
an equilibrium index is found */
for (i = 0; i < n; ++i) {
/* get left sum */
leftsum = 0;
for (j = 0; j < i; j++)
leftsum += arr[j];
/* get right sum */
rightsum = 0;
for (j = i + 1; j < n; j++)
rightsum += arr[j];
/* if leftsum and rightsum are same,
then we are done */
if (leftsum == rightsum)
return i;
}
/* return -1 if no equilibrium index is found */
return -1;
}
// Driver code
public static void main(String[] args)
{
EquilibriumIndex equi = new EquilibriumIndex();
int arr[] = { -7, 1, 5, 2, -4, 3, 0 };
int arr_size = arr.length;
System.out.println(equi.equilibrium(arr, arr_size));
}
}
// This code has been contributed by Mayank Jaiswal
Time Complexity: O(n^2)
Method 2 (Tricky and Efficient)
The idea is to get the total sum of the array first. Then Iterate through the array and keep updating the left sum which is initialized as zero. In the loop, we can get the right sum by subtracting the elements one by one. Thanks to Sambasiva for suggesting this solution and providing code for this.
1) Initialize leftsum as 0
2) Get the total sum of the array as sum
3) Iterate through the array and for each index i, do following.
a) Update sum to get the right sum.
sum = sum - arr[i]
// sum is now right sum
b) If leftsum is equal to sum, then return current index.
// update leftsum for next iteration.
c) leftsum = leftsum + arr[i]
4) return -1
// If we come out of loop without returning then
// there is no equilibrium index
The image below shows the dry run of the above approach:
Below is the implementation of the above approach:
Java
// Java program to find equilibrium
// index of an array
class EquilibriumIndex {
int equilibrium(int arr[], int n)
{
int sum = 0; // initialize sum of whole array
int leftsum = 0; // initialize leftsum
/* Find sum of the whole array */
for (int i = 0; i < n; ++i)
sum += arr[i];
for (int i = 0; i < n; ++i) {
sum -= arr[i]; // sum is now right sum for index i
if (leftsum == sum)
return i;
leftsum += arr[i];
}
/* If no equilibrium index found, then return 0 */
return -1;
}
// Driver code
public static void main(String[] args)
{
EquilibriumIndex equi = new EquilibriumIndex();
int arr[] = { -7, 1, 5, 2, -4, 3, 0 };
int arr_size = arr.length;
System.out.println("First equilibrium index is " +
equi.equilibrium(arr, arr_size));
}
}
// This code has been contributed by Mayank Jaiswal
OutputFirst equilibrium index is 3
Output:
First equilibrium index is 3
Time Complexity: O(n)
Method 3 :
This is a quite simple and straightforward method. The idea is to take the prefix sum of the array twice. Once from the front end of array and another from the back end of array.
After taking both prefix sums run a loop and check for some i if both the prefix sum from one array is equal to prefix sum from the second array then that point can be considered as the Equilibrium point.
Java] [tabby title=java
// Java program to find equilibrium
// index of an array
class GFG{
static int equilibrium(int a[], int n)
{
if (n == 1)
return (0);
int[] front = new int[n];
int[] back = new int[n];
// Taking the prefixsum from front end array
for (int i = 0; i < n; i++)
{
if (i != 0)
{
front[i] = front[i - 1] + a[i];
}
else
{
front[i] = a[i];
}
}
// Taking the prefixsum from back end of array
for (int i = n - 1; i > 0; i--)
{
if (i <= n - 2)
{
back[i] = back[i + 1] + a[i];
}
else
{
back[i] = a[i];
}
}
// Checking for equilibrium index by
//comparing front and back sums
for(int i = 0; i < n; i++)
{
if (front[i] == back[i])
{
return i;
}
}
// If no equilibrium index found,then return -1
return -1;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { -7, 1, 5, 2, -4, 3, 0 };
int arr_size = arr.length;
System.out.println("First Point of equilibrium " +
"is at index " +
equilibrium(arr, arr_size));
}
}
// This code is contributed by Lovish Aggarwal
OutputFirst Point of equilibrium is at index 3
Time Complexity: O(N)
Space Complexity: O(N)
Please refer complete article on Equilibrium index of an array for more details!
Similar Reads
Java Program for Maximum equilibrium sum in an array Given an array arr[]. Find the maximum value of prefix sum which is also suffix sum for index i in arr[]. Examples : Input : arr[] = {-1, 2, 3, 0, 3, 2, -1} Output : 4 Prefix sum of arr[0..3] = Suffix sum of arr[3..6] Input : arr[] = {-2, 5, 3, 1, 2, 6, -4, 2} Output : 7 Prefix sum of arr[0..3] = Su
4 min read
Java Program for Number of local extrema in an array You are given an array on n-elements. An extrema is an elements which is either greater than its both of neighbors or less than its both neighbors. You have to calculate the number of local extrema in given array. Note : 1st and last elements are not extrema.Examples : Input : a[] = {1, 5, 2, 5} Out
2 min read
Java Program to Find Sum of Array Elements Given an array of integers. Write a Java Program to find the sum of the elements of the array. Examples: Input : arr[] = {1, 2, 3} Output : 6 1 + 2 + 3 = 6 Input : arr[] = {15, 12, 13, 10} Output : 50 15 + 12 + 13 + 10 = 50 An array is a data structure that contains a group of elements. Typically th
3 min read
Java Program to Print the Smallest Element in an Array Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. Example: arr1[] = {2 , -1 , 9 , 10} output : -1 arr2[] = {0, -10, -13, 5} output : -13 We need to find and print the smallest value
3 min read
Java Program for Range Queries for Frequencies of array elements Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type. Examples:  Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; l
2 min read
Java Array Programs An array is a data structure consisting of a collection of elements (values or variables), of the same memory size, each identified by at least one array index or key. An array is a linear data structure that stores similar elements (i.e. elements of similar data type) that are stored in contiguous
4 min read
Determine the Upper Bound of a Two Dimensional Array in Java Multidimensional arrays in Java are common and can be termed as an array of arrays. Data in a two-dimensional array in Java is stored in 2D tabular form. A two-dimensional array is the simplest form of a multidimensional array. A two-dimensional array can be seen as an array of the one-dimensional a
3 min read
Java Program to Print the Elements of an Array Present on Even Position The task is to print all the elements that are present in even position. Consider an example, we have an array of length 6, and we need to display all the elements that are present in 2,4 and 6 positions i.e; at indices 1, 3, 5. Example: Input: [1,2,3,4,5,6] Output: 2 4 6 Input: [1,2] Output: 2 Appr
2 min read
Sort and Search an Element in Java In Java sorting and searching an element in an array is very easy. Unlike C, where we have to make all the functions to work, Java has inbuilt functions to do the same work. To sort an array there is a sort function and to search an element in a sorted array there is a binarySearch() function. To le
3 min read
Java Program to Print the Elements of an Array Present on Odd Position An array stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. In an array, if there are "N" elements, the array iteration starts from 0 and ends with "N-1". The odd positions in the array are those with even indexing and vice versa. E
3 min read