Can you tell me where is mistake?


Can you tell me some other efficient approach.

@raj.verma5454,
The problem breaks down to, find the last element that is greater than current element, so this can be done by just a single stack.

Maintain a stack that stores indexes of elements:

Case 1: a[i] <= a[s.top()]

  • Simply push the current index on top of stack, i.e s.push(i);

Case 2: a[i] > a[s.top()]

  • Now all the previous elements that are smaller than a[i] are useless for future, so pop all of them, i.e, pop till a[s.top()] <a[I], and then s.push(i);

okk , but can you tell me for which test case my code failed?

I am stuck. please help me

@raj.verma5454,
Check your code against this test case:

  • Input :
    6
    1 2 3 1 2 4

  • Output:
    1 2 3 1 2 6

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.