Greator Element stack

why 1 Test case fails?

you have not write the code for circular array

To find the next greater number for element Ai , start from index i + 1 and go uptil the last index after which we start looking for the greater number from the starting index of the array since array is circular.

Please Modify my code .I’m not getting it.

Algorithm

  • Initialize a stack to store the indices of the array and an array nge[] of size N which stores the next greater element for each array element.
  • Traverse the array and for each index, perform the following:
  • If the stack is non-empty and the current ith array element is greater than the top element of the stack, then pop the top element of the stack and update nge[st.top()] by storing arr[i % N] in it. Repeat this until the stack is empty or the current element is less than the element at the top of the stack.
  • If the stack is empty or the current element is less than the top of the stack, push (i % N) into the stack.
  • After a single traversal of N elements, the stack contains the elements which do not have a next greater element till the (N – 1)th index. As the array is circular, consider all the elements from the 0th index again and find the next greater element of the remaining elements.
  • Since the array is traversed 2 times, it is better to use i % N instead of i.
  • After completing the above steps, print the array nge[].

Reference Code

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.