154. Next Greater Element
Challenge1000 ms256 MBSolved by 0%
For each element, print the first value to its RIGHT that is strictly larger
than it, or -1 if there is none.
Print all n answers on one line, separated by single spaces.
For [4, 5, 2, 25] the answers are 5 25 25 -1.
Constraints - `1 ≤ n ≤ 200000` - `-1000000000 ≤ a[i] ≤ 1000000000`
Input
The first line contains an integer n.
The second line contains n space-separated integers.
Output
Print n integers on ONE line, separated by single spaces, each element's answer, or -1.
Input4
4 5 2 25
Output5 25 25 -1
Noteis the worked example from the statement
Input4
4 3 2 1
Output-1 -1 -1 -1
Noteis descending, so nothing has a greater element to its right
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.
Hint 1Where to start
Hint 2The approachOpen hint 1 first. This one carries on from it.
Hint 3PseudocodeOpen hint 2 first. This one carries on from it.
Hint 4Full solutionOpen hint 3 first. This one carries on from it.