Problem Solving‎ > ‎

### Next greater element

 Problem:Given an array, print the next greater element for every element. Elements for which no greater element exist, print next greater element as -1.For the elements of the array [4, 5, 2, 25, 20, 11, 13, 21, 3] greater elements are as follows.4 --> 55 --> 252 --> 2525 --> -120 --> 2111 --> 1313 --> 2121 --> -13 --> -1Solution : O(n)1. Take stack A.2. Initially the stack is empty. Traverse the array from left to right. Do for every elementa. if the stack is empty push the element in the stackb. if the stack is non empty keep on popping elements from the stack till element popped < current element. The next greater element for every popped element would be the current element. If element popped > current element. Push popped element and then current element on the stack.3. When the traversal is complete, if the stack is nonempty pop elements from the stack and set the values of next greater element for these popped element as -1.eg. for array [2, 25, 20, 11, 21, 3]stack A -> emtpy1. push element 2 on stack A->22. pop 2 from the stack. Compare it with 25 since 2 < 25 set next greater element of 2 as 25.A->253. pop 25 from the stack. 25 > 20 . Push 25 on the stack. Push 20 on the stack.A->25->204. pop 20 from the stack. 20>11. Push 20 on the stack. Push 11 on the stack.A->25->20->115. pop 11 from the stack. 11 < 21. Set next greater element of 11 as 21. Pop 20 from the stack. 20 < 21. Set next greater element of 20 as 21. Pop 25 from the stack. 25 > 21. Push 25 on stack. Push 21 on stack.A->25->216. pop 21 from the stack. 21 > 3. Push 21 on stack. Push 3 on stack.A->25->21->3Set the value of next greater elements for all the elements present in the stack as -1.