Step 2/3 Iterate through the rest of the elements in a for-loop.
- Mark the iterated on/current element as the
next
element. - If stack is not empty, compare
top
element of the stack withnext
. - If
next
is greater than the top element,pop
the element from the stack. What this means is that we've determinednext
is the next greater element for the popped number. - While the popped element is smaller than
next
, keep popping off the top of the stack. As the logic follows,next
becomes the next greater element for all the popped elements.
