Home » Data Structure & Algorithms » Next Greater Element of an array using stack

Next Greater Element of an array using stack

Question :

WAP to find next greater element of an array using stack

Algorithm :

Iterative Solution :
Step 1 : Push the first element of the array to the stack.Follow step 2 from 2nd element of the array.
Step 2 : Mark the current element as next and top element of stack as currentStack.If stack is not empty, then pop an element from stack and compare it with next.If next is greater than the popped element, then next is the next greater element for the popped element. Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements.If next is smaller than the popped element, then push the popped element back.
Step 3 : pop all the elements left in the stack and print -1 as next element for them.

Program :

OutPut :

 
 


Leave a comment

Your email address will not be published. Required fields are marked *

2 × two =