How can i find next greater element in same order as given array?

How can i find ans in same order as given array , in O(n) time and constant space.??

@Vipin_coder,

  1. we can start iterating from the last element(nth) to the first(1st) element
    The benefit is that when we arrive at a certain index his next greater element will be already in stack and we can directly get this element while at the same index.

  2. After reaching a certain index we will pop the stack till we get the greater element on top from the current element and that element will be the answer for current element

  3. If stack gets empty while doing the pop operation then the answer would be -1
    Then we will stored the answer in an array for the current index.

There is no extra space required if you want to print the next greater of each element in reverse order of input(means first, for the last element and then for second last and so on till the first element)

i don’t want to print in reverse order, and i don’t want to reverse the ans after getting reverse order<

I want to print ans in first to last element in constant space with O(n) Time

@Vipin_coder,
I have replied to you on chat

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.