Next Greater Element

Will there be a wrong answer sowing message if the order are not same as given in the example.
For Example:
(this will be the output if we apply brute force)

2->3

1->3

3->8

8->-1

6->7

7->-1

5->-1

(this will be the output using stack and o(n) solution)

1->3

2->3

3->8

6->7

5->-1

7->-1

8->-1

as shown above the order are different.

2nd Doubt
By seeing at the o(n) solution order is there any way we can find hint that we are going to use stack(not only for this question but for other stack questions as well)

@ubaidshaikh9999
you change the order of both brute force solution and stack solution depeding upon the problem statement.you just simple store the next greater element of each element in an arrays and print it in any order you want.

for 2nd doubt its totally depend upon the question if constrained are in such that n^2 approach wouldn’t work then you can think think of stack.

Can u plz explain how we can change the order of output in brute force

@ubaidshaikh9999
you can simply make a pair class having attributes index, value,next_gre and create an array of pair class then after finding the next greater element of each value you can create pair for each element add this pair to the array of pair then sort the array with respect to value.

then print the next_gre element of each pair in the array starting form 0th index.

@ubaidshaikh9999
please mark your doubt as resolved in my doubt section and rate me as well.

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.