In the Given question

In the given question array is already sorted or not?

@ravi.cs18 no it is not mentioned in the problem statement.it is not necessary that given array will be sorted.

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.

please give me some glimpse that how it can be done>

The elements can be in any random order.
Brute Force method of using 2 loops will give you O(n^2) time complexity and will result in a TLE.
But it can also be solved in O(n) complexity in the following way -

  1. Push the first element to stack.
  2. Pick rest of the elements one by one and follow the following steps in loop.
    a. Mark the current element as next.
    b. If stack is not empty, compare top element of stack with next.
    c. If next is greater than the top element, pop element from stack. next is the next greater element for the
    popped element.
    d. Keep popping from the stack while the popped element is smaller than next. next becomes the next
    greater element for all such popped elements
  3. Finally, push the next in the stack.
  4. After the loop in step 2 is over, pop all the elements from stack and print -1 as next element for them.

@ravi.cs18 Please mark your doubt as resolved if you are satisfied.

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.