×

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

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

Difference between C, C++, java

C Language: C language is a procedure oriented language. It has been invented by Dennis Ritchie in the year 1970. It is one of the computer programming language. The purpose of...

3 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Gregorian Calendar Java Current Date

GregorianCalendar class uses the Gregorian and Julian calendars. Dates are calculated by projecting present laws forever backward and forward in time. As a consequence, GregorianCalendar may be utilised to create...

8 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.