Equilibrium Index of an Array in Java
In this section, we will learn what is equilibrium index in an array and how to find the equilibrium index through a Java program.
If the sum of lower indices elements is equal to the sum of higher indices elements is called an equilibrium index of an array
For example, consider the array [-7, 1, 5, 2, -4, 3, 0], where:
a=-7, a=1, a=5, a=2, a=-4, a=3, a=0
Let's find the equilibrium index. According to the definition:
The sum of elements at lower indices is = a+a+a = -7+1+5 = -1
The sum of elements at higher indices is = a+a+a = -4+3+0 = -1
We observe that the sum of elements at lower indices is equal to the sum of elements at higher indices. Hence, for the given array an equilibrium index is 3.
In the above array, 6 is also an equilibrium index because the sum of a to a is 0, and the value of index a is 0.
Methods to find the Equilibrium Index
There are the three methods to find the equilibrium index of an array:
Brute Force Approach
In this approach, we use two loops. The outer loop iterates over the array and the inner loop checks if there exists an equilibrium index or not. The idea is to find the sum of elements for every range of indexes and observe if exists an equilibrium index. It takes O(n2) time and space complexity O(1) to solve the problem.
Let's implement the above logic in a Java program.
Equilibrium Index is: 3
In the above approach, we have used nested loop for calculating the left and right sum for each value of i. It performs n(n-1) summation operations.
Using an Iterative Approach
The approach uses some extra space. In this approach, we store the prefix sum of the array. It keeps track the sum of all the elements up to any index of the array. Now, we need to track the sum of values to the right of the current index.
To find the sum of values to the right of current index, subtract the value at the current index. Now compare the lsum and rsum, if they are equal the current index is equilibrium index.
It's time and space complexity are O(n). Let's implement the above algorithm in a Java program.
Equilibrium Index is: 5
Using an Incremental Approach
The incremental approach is the same as iterative approach except some things. The difference between the approach and the previous approach (iterative approach) is that we need not to store the prefix sum. Instead, we keep track of the left sum at the same time while iterating over the array. In this approach, first we calculate the total sum of the array. To get the right sum, inside the loop we subtract the element one by one. It's time and space complexity is O(n) and O(1), respectively.
Let's implement the above approach in a Java program.
Equilibrium Index is: 4
Equilibrium Index is: -1