×

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where:

a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5

Now according to the definition:

The sum of the elements at lower index positions are=a[0]+a[1]=-4+5=1

The sum of the elements at higher index positions are =a[2]+a[3]=6+-5=1

We observe that the sum of the elements at lower and higher index positions is equal. So, the equilibrium index value is 2.

Methods to calculate the equilibrium index

There are three ways to determine an array's equilibrium index:

1. Using a brute force approach

2. An incremental approach

3. An iterative approach

Brute force approach

In this method, we implement two loops. The inner loop determines whether or not an equilibrium index exists, while the outer loop iterates across the array. The objective is to compute the elemental total for each index range and determine whether an equilibrium index exists. The problem can be solved in O(n2) time with O(1) space.

Algorithm

  • The array is iterated.
  • Finding the left and right index values for the current index are found. Should find the total components to the left and right of the current index for each index.
  • The current index is an equilibrium if the Lsum and the Rsum are equal.
  • Otherwise, return 0.

Implementation

Filename: EquilibriumIndexEx1.java

//Java Program for finding equilibrium index
//importing packages
import java.io.*;
Import java.util.*;
public class EquilibriumIndexEx1  
{  
// function for finding the index value 
static int eqlindex(int arr[], int num)  
{  
int i, j;  
// Lsum denotes the sum of left elements, and Rsum denotes the sum of Right elements
int Lsum, Rsum;  
for (i = 0; i < num; ++i)   
{  
Lsum = 0;  
// the sum of values upto the current index  
for (j = 0; j < i; j++)  
Lsum = Lsum + arr[j];  
Rsum = 0;  
// finding the sum from the current value to the last index
for (j = i + 1; j < num; j++)  
Rsum = Rsum + arr[j];  
//if Rsum and Lsum are equal returns i (equilibrium index), else return -1  
if (Lsum == Rsum)  
return i;  
}  
return -1;  
}  
public static void main(String args[])  
{  
int arr[] = {9, 11, 7, 8, 8, 9, 10};  
int l = arr.length;  
System.out.print("The Equilibrium Index position is: ");  
System.out.println(eqlindex(arr,l));  
}  
}  

Output

The Equilibrium Index position is: 3

Applying an Iterative Process

This process made advantage of some excess space. With this method, we save the array's prefix sum. It maintains track of the total of all elements up to an array index. The sum of numbers to the right of the current index must now be checked.

Subtract the number at the current index to get the total numbers to the right. The current index is the equilibrium index when the Lsum and Rsum are equivalent.

Algorithm

  • Allocate some additional space to store the array's prefixed sum.
  • Identify the array's total sum and save it as the correct sum (Rsum).
  • Check the Rsum and Lsum values by iterating over the array.
  • i should be returned if Rsum and Lsum are equal (current index).
  • Otherwise, return 0.

The time complexity for implementation is O(n).

Filename: EquilibriumIndexEx2.java

//Java Program for finding the equilibrium index
import java.io.*;
import java.util.*;
public class EquilibriumIndexEx2  
{  
static int eqlindex(int arr[], int num)  
{  
//Lsum and Rsum stand for left and right sums, respectively. 
int prefixs[]=new int[num];  
// the array of the sum
for (int i = 0; i < num; i++)  
{  
if(i==0)   
prefixs[i] = arr[i];  
else prefixs[i] = arr[i] + prefixs[i-1];  
}  
int Rsum = prefixs[num-1];  
for(int i = 0 ; i < num; i++)  
{  
Rsum = Rsum - arr[i];  
int Lsum = prefixs[i+1];  
if(Rsum==Lsum)  
return i + 1;  
}  
return -1;  
}  
public static void main(String args[])  
{  
int arr[] = {0, -3, 6, -5, -1, 6, -2, 0};  
int l = arr.length;  
System.out.print("The Equilibrium Index value is: ");  
System.out.println(eqlindex(arr,l));  
}  
}  

Output

The Equilibrium Index value is: 3

A Step-by-Step Approach

The incremental approach is similar to the iterative technique, with a few exceptions. It has O(n) time complexity and O(1) space complexity. The method differs from the prior(iterative method) in that we do not need to keep the prefix sum. Instead, while iterating through the array, we maintain track of the left sum. In this method, we start by computing the array's overall sum. To obtain the correct value.

Steps in an Algorithm

  • Put the Tsum variable's value as the array's total.
  • During each iteration of the array, add the value at the current index i to the Lsum and remove the value at the present index from the Rsum to maintain track of the Lsum.
  • The current index returns if Lsum and Rsum are equal (i).
  • Otherwise, return 0.

Filename: EquilibriumIndexEx3

//Java Program for finding the Equilibrium index
import java.io.*;
import java.util.*;
public class EquilibriumIndexEx3  
{  
static int eqbmindex(int arr[], int num)  
{  
//Lsum indicates the left indexes sum, and Rsum indicates the right indexes 
int Rsum = 0;  
int Lsum = 0;  
// The Total sum of the array
for (int i = 0; i < num; ++i)  
Rsum = Rsum + arr[i];  
for (int i = 0; i < num; ++i)   
{  
//The Rsum is updated
Rsum = Rsum - arr[i];  
//it checks the left and right array sum
if (Lsum == Rsum)  
return i;  
Lsum = Lsum + arr[i];  
}  
return -1;  
}  
public static void main(String args[])  
{  
int arr[] = {1, 3, 6, 4, 1, 0, 3, 2, 5, 4};  
int l = arr.length;  
System.out.print("The Equilibrium Index is: ");  
System.out.println(eqbmindex(arr,l));  
}  
}  

Output

The Equilibrium Index is: 4

Related Topics

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Java String replaceAll() method

Java String replaceAll() method returns a String replacing all the sequence of characters matching regular expression i.e regex and replacement string. Syntax: public String replaceAll(String regex, String replacement) Parameters: regex : regular expression replacement :...

1 minute read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of...

6 minutes read.

Merge Sort in Java

Merge Sort in Java Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort. 1) Divide the...

5 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be...

4 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.