Find the next greater

in this question it is mention that stack is of indexes but stack for element is also working fine can anyone explain with one test case ??

hey @shampblocks if you use elements instead of indexes that you would know the next greater number for that element but how would you store it, you need to store it at the index of that element that s why stack of indices is suggested.

I will store it in stack same as I am doing with index… And check for next element and rest of the things are same…

since the elements for which the next greater elements has been found needs to popped out, answer needs to be stored in a vector or a array.

But in the algorithm we are not popping when next greater element we are pushing it and for number if are not getting next greater element in stack top then we are popping till we get next greater element…

yes we are pushing in the greater element, but we are popping out the elements for which the that element is next greater element you need to store answer for those elements
Please refer to this article for more help:

But this is for linear but in this question we have to check for circularly…

in that case make the array size 2*n and append the array onto itself i.e if the given array was 1 2 3 new one would be 1 2 3 1 2 3. Now run the algorithm given above the first n elements should contain correct answers.

1 Like

Oh great sir thanks…

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.