Next Greater Element in an Array | JavaScript Implementation

Manan Kumar Gupta
2 min readOct 3, 2021

--

We will be implementing JavaScript code to find the Next Greater Number in the Array.

Question: The first greater element on the right side of x in the array is the Next greater Element for an element x. Consider the next greater element as -1 for elements for which there is no greater element.

Let understand the problem first with an examples:

let arr = [ 1000 , 8 , 100 , 120 , 5 ,  1]
//Output:
[-1 , 100 , 120 , -1 , -1 , -1]

Implementation

  1. Push the first element to stack.
  2. Pick rest of the elements one by one and follow the following steps in loop.
    a. Mark the current element as next.
    b. If stack is not empty, compare top element of stack with next.
    c. If next is greater than the top element, Pop element from the stack. next is the next greater element for the popped element.
    d. Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements.
  3. Finally, push the next in the stack.
  4. After the loop in step 2 is over pop all the elements from the stack and print -1 as the nest element from them.
function getNGR(arr){
var queue = [];
queue.push(arr[0]);
for(let i = 1;i < arr.length;i++){
if(queue.length == 0){
queue.push(arr[i]);
continue;
}
while(!(queue.length == 0 ) && s[queue.length - 1] < arr[i]){
console.log(s[queue.length - 1], arr[i])
queue.pop()
}
queue.push(arr[i])
}
while(queue.length !=0 ){
console.log(s[queue.length - 1], -1)
queue.pop()
}
}
console.log(getNGR([11, 13, 21, 3]))
Output:
8 100
100 120
1 -1
5 -1
120 -1
1000 -1

I hope you find this post as useful to read more the question click on the link.
Similar question: Next Smaller Number.

--

--

Manan Kumar Gupta
Manan Kumar Gupta

Written by Manan Kumar Gupta

I am Frontend Developer, exploring the power of Javascript. I have worked on Angular, ReactJS and React Native.

No responses yet