JavaScript Program for Equilibrium index of an array


The position where the sum of the elements to its left and right equals one another is known as the equilibrium index of an array. To put it another way, if we take a look at an array of size n, the equilibrium index i is a point such that −

arr[0] + arr[1] + ... + arr[i-1] = arr[i+1] + arr[i+2] + ... + arr[n-1]

where i is the equilibrium index and arr is the input array. We may alternatively state that the array is divided into two parts by the equilibrium index i such that the total of the elements in the left and right sections are equal.

For Example −

Let's consider the following array −

A = [2, 4, -3, 0, -4, 6, 1]
In this sequence, the equilibrium index is 3 (element 0) because (2+4-3) = (-4+6+1).
It is also balanced with another equilibrium index 5 (element 6) because (2+4-3+0-4) = (1).

Problem Statement

Given an array of integers, find the index of the equilibrium point of the array. If there is no equilibrium point, return -1.

Example

Consider an array of integers −

[3, 7, 1, 5, 10, 2, 7, 9]

The equilibrium index of this array is 4 because the sum of elements before the index (3+7+1+5 = 16) is equal to the sum of elements after the index (2+7+9 = 18).

Method 1: Using the Loop

Use two loops: the outer loop iterates through all of the elements, while the inner loop determines whether or not the current index selected by the outer loop is an equilibrium index. The time complexity of this approach is O(n2), which will be explained later. The usage of two loops is simple. The goal is to find the sum of elements for each range of indexes and see if an equilibrium index exists. The outer loop traverses the array, while the inner loop assesses whether or not there is an equilibrium index.

Algorithm

  • Use two loops

  • Outer loop iterates through all the elements and the inner loop checks out whether the current index picked by the outer loop is either an equilibrium index or not.

  • Run a loop through the array

  • For each index, find the sum of elements towards the left and right of the current index

  • If the left_sum and right_sum are equal, then the current index is the equilibrium index

  • Otherwise, return -1

  • The time complexity of this solution is O(n2)

Example

<!DOCTYPE html>
<html>
<body>
   <h3>Input Array: [-7, 1, 5, 2, -4, 3, 0]</h3>
   <script>
      
      // Input array
      const arr = [-7, 1, 5, 2, -4, 3, 0];
      
      // Flag to check if equilibrium index is found or not
      let equilibriumIndexFound = false;
      
      // Loop through each index i of the array
      for (let i = 0; i < arr.length; i++) {
         let leftSum = 0;
         let rightSum = 0;
         
         // Calculate the sum of elements to the left of i
         for (let j = 0; j < i; j++) {
            leftSum += arr[j];
         }
         
         // Calculate the sum of elements to the right of i
         for (let j = i + 1; j < arr.length; j++) {
            rightSum += arr[j];
         }
         
         // Check if the sum of elements to the left and right of i is equal
         if (leftSum === rightSum) {
            document.body.innerHTML += `The equilibrium index of the array is ${i}`;
            equilibriumIndexFound = true;
            break;
         }
      }
      
      // Check if equilibrium index is not found
      if (!equilibriumIndexFound) {
         document.body.innerHTML += `There is no equilibrium index in the array`;
      }
   </script>
</body>
</html>

Please keep in mind that the preceding code is only for demonstration purposes and should not be used in production because it is not optimised. It has an O(n2) time complexity, which is inefficient for big arrays.

Method 2: Prefix Sum

Another way to calculate an array's equilibrium index is the prefix sum method. With this method, we first compute the array's prefix sum, which is the sum of elements from the array's beginning to the current index. Then, using the prefix sum, we loop through the array, checking if the total of elements to the left of the current index equals the sum of elements to the right of the current position.

Algorithm

  • Determine the array's prefix sum.

  • Iterate through the array and use the prefix sum to see if the sum of items to the left of the current index equals the sum of elements to the right of the current position.

  • Return that index as the equilibrium index if the sum of the components to the left equals the sum of the elements to the right.

  • If no equilibrium index exists, return -1.

Example

<!DOCTYPE html>
<html>
<body>
   <h3>Equilibrium Index</h3>
   <script>
      function equilibriumIndex(arr) {
         let n = arr.length;
         
         // Calculate the prefix sum of the array
         let prefixSum = [];
         prefixSum[0] = arr[0];
         for (let i = 1; i < n; i++) {
            prefixSum[i] = prefixSum[i - 1] + arr[i];
         }
         
         // Iterate through the array and check for equilibrium index
         for (let i = 0; i < n; i++) {
            let leftSum = (i == 0) ? 0 : prefixSum[i - 1];
            let rightSum = prefixSum[n - 1] - prefixSum[i];
            if (leftSum == rightSum) {
               return i;
            }
         }
         
         // No equilibrium index found
         return -1;
      }
      let arr = [-7, 1, 5, 2, -4, 3, 0];
      
      // Print the array
      document.write("Array: " + arr + "<br>");
      let result = equilibriumIndex(arr);
      if (result == -1) {
         document.write("No equilibrium index found");
      } else {
         document.write("Equilibrium index is " + result);
      }
   </script>
</body>
</html>

Note − The time complexity of the prefix sum approach to find the equilibrium index of an array is O(n), where n is the size of the array

Method 3: Two Pointers

In this method, we can keep track of two pointers, one at the start and one at the end of the array. With these two pointers, we can then calculate the left and right sums and shift the pointers towards each other until we obtain the equilibrium index.

Algorithm

  • Initialize leftSum and rightSum as 0 and n-1 as the right pointer.

  • Traverse the array from left to right.

  • At each element, add the element to the leftSum and subtract it from the rightSum.

  • If leftSum equals rightSum, return the current index as the equilibrium index.

  • If no equilibrium index is found, return -1.

Example

<!DOCTYPE html>
<html>
<body>
   <h3>Equilibrium index of an array - Two Pointers Approach</h3>
   <p id="input"></p>
   <p id="output"></p>
   <script>
      const arr = [-7, 1, 5, 2, -4, 3, 0];
      const n = arr.length;
      let leftSum = 0;
      let rightSum = 0;
      document.getElementById("input").innerHTML = "Input Array: " + arr.join(", ");
      for (let i = 0; i < n; i++) {
         rightSum += arr[i];
      }
      for (let i = 0; i < n; i++) {
         rightSum -= arr[i];
         if (leftSum === rightSum) {
            document.getElementById("output").innerHTML = "Equilibrium index: " + i;
            break;
         }
         leftSum += arr[i];
      }
      if (document.getElementById("output").innerHTML === "") {
         document.getElementById("output").innerHTML = "No equilibrium index found";
      }
   </script>
</body>
</html>

Note − The time complexity of the prefix sum approach to find the equilibrium index of an array is O(n), where n is the size of the array.

Conclusion

In this blog we have talked about finding the equilibrium index of an array by various methods. Some of them are using loop, prefix sum and two pointer approaches. Ho[e you found this information useful.

Updated on: 10-Apr-2023

276 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements