How to solve this using stacks? and i just used sorting for this, i got one test case right. What is wrong with this:
Find the greater element Stacks
Hello @Kishan-Mishra-2464674013761441,
The sorting approach is good but this would not work for this question:
As you are sorting the array, the relative position of elements is changing.
i.e. the order of elements is changing.
Also, it is written in the question:
print the next greater number for every element.
Let’s understand this with the help of an example:
4
3 2 1 4
Expected Output:
4 4 4 -1
Your Output:
2 3 4 -1
Explanation:
- the next greater element on right of 3 is 4 int the input array.
- the next greater element on right of 2 is 4 int the input array.
- the next greater element on right of 1 is 4 int the input array.
- Considering it a circular array, if we check on the right of 4 (i.e. from i=0 to 2), there is no element greater than 4, so print -1.
But, if we would sort the array, their relative position will change, leading to a wrong output.
Hope, this would help.
Give a like, if you are satisfied.
It is now working for the test case provided by you. But still getting wrong answer in one of the test cases.
I tested your code for different possible test-cases that i can think of and here’s the result:
Example 1:
4
1 4 3 2
Expected Output:
4 -1 4 4
Your Output:
4 -14 4
Here, the mistake is easily observable that you have to print space after -1.
Example2:
Even after correcting above mentioned mistake, the code will not pass the second test case.
4
4 4 4 4
Expected Output:
-1 -1 -1 -1
Your Output:
-1 -1 -1
Where’s the fourth -1?
Correct it and your code will pass both the test cases.
Give a like, if it works.
Thanks!
It helped a lot.
Anytime.
Please, mark this doubt as resolved if you have no more issues regarding this thread.