Equilibrium Index of an Array in JavaIn this section, we will learn what is equilibrium index in an array and how to find the equilibrium index through a Java program. Equilibrium IndexIf 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[0]=-7, a[1]=1, a[2]=5, a[3]=2, a[4]=-4, a[5]=3, a[6]=0 Let's find the equilibrium index. According to the definition: The sum of elements at lower indices is = a[0]+a[1]+a[2] = -7+1+5 = -1 The sum of elements at higher indices is = a[4]+a[5]+a[6] = -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[0] to a[5] is 0, and the value of index a[6] is 0. Methods to find the Equilibrium IndexThere are the three methods to find the equilibrium index of an array:
Brute Force ApproachIn 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. Algorithm Steps
Let's implement the above logic in a Java program. EquilibriumIndexExample1.java Output: 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 ApproachThe 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. Algorithm Steps
It's time and space complexity are O(n). Let's implement the above algorithm in a Java program. EquilibriumIndexExample2.java Output: Equilibrium Index is: 5 Using an Incremental ApproachThe 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. Algorithm Steps
Let's implement the above approach in a Java program. EquilibriumIndexExample3.java Output 1: Equilibrium Index is: 4 Output 2: Equilibrium Index is: -1 |