Finding distance to next greater element in JavaScript


Problem

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

Our function should construct a new array for the input in which each corresponding element is the distance to the next greater element than the current element, and if there is no greater element to the right of the current element, we should push 0 for that corresponding element in the res array and finally we should return this array.

For example, if the input to the function is

Input

const arr = [12, 13, 14, 11, 16, 10, 12, 17, 19, 18];

Output

const output = [1, 1, 2, 1, 3, 1, 1, 1, 0, 0];

Output Explaination

Because the next greater element to 12 is 13, 1 block away,

Next greater to 13 is 14, 1 block away,

Next greater to 14 is 16, 2 blocks away and so on.

Following is the code −

Example

 Live Demo

const arr = [12, 13, 14, 11, 16, 10, 12, 17, 19, 18];
const findNextGreater = (arr = []) => {
   const stack = []
   const res = new Array(arr.length).fill(0)
   for (let i = 0; i < arr.length; i++) {
      while (arr[i] > arr[stack[stack.length - 1]] && stack.length > 0) {
         const index = stack.pop()
         res[index] = i - index
      }
      stack.push(i)
   };
   return res
};
console.log(findNextGreater(arr));

Output

[1, 1, 2, 1, 3, 1, 1, 1, 0, 0]

Updated on: 24-Apr-2021

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements