Next Greater Element in Circular Array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Circular Array

An array in which the next element of the last element is the first element of the array is often termed as circular.

Obviously, there exists no such mechanism to store data like this, data will still be stored in continuous memory blocks and circular arrays are more like an idea than reality.

Problem

We are required to write a JavaScript function that takes in a circular array of Integers, arr, as the first and the only argument.

The function should then construct and return an array that contains the next greater element for each corresponding element of the original array. The Next Greater Number of a number, say num, is the first greater number to its traversing-order (right in our case) next in the array, which means we could search circularly to find its next greater number. If that doesn't exist, we should consider -1 for this number.

For example, if the input to the function is −

const arr = [7, 8, 7];

Then the output should be −

const output = [8, -1, 8];

Output Explanation

Next greater to both the 7s in the array is 8 and since the array is circular but for 8, there’s no greater element hence we put -1 for it.

Example

The code for this will be −

 Live Demo

const arr = [7, 8, 7];
const nextGreaterElement = (arr = []) => {
   const res = [];
   const stack = [];
   if (!arr || arr.length < 1){
      return res;
   };
   for (let i = 0; i < arr.length; i++) {
      while (stack.length > 0 && arr[stack[stack.length - 1]] < arr[i]) {
         const small = stack.pop();
         res[small] = arr[i];
      };
      stack.push(i);
   }
   for (let i = 0; i < arr.length; i++) {
      while (stack.length > 0 && arr[stack[stack.length - 1]] < arr[i]) {
         const small = stack.pop();
         res[small] = arr[i];
      };
   }
   const rem = stack.length;
   for (let i = 0; i < rem; i++) {
      res[stack.pop()] = -1;
      }
      return res;
   };
console.log(nextGreaterElement(arr));

Code Explanation:

While iterating over the array if we find an element which is bigger than one in the stack, we set res[small] to the current larger element found.

Now, we again begin from the start of arr and deal with elements for which we couldn't find a next bigger element in the previous for loop. Finally, still there would be some elements for which there was no next greater element.

Output

And the output in the console will be −

[8, -1, 8]
raja
Published on 03-Mar-2021 06:13:51
Advertisements