You are given an array of n integers. For each position i, its next greater element is the value of the first element that appears strictly after i and is strictly greater than a[i]. If no such element exists, the answer for that position is -1.
Output the answer for every position, in order.
Line 1: an integer n.
Line 2: n space-separated integers a[0] a[1] ... a[n-1].
A single line with n space-separated integers: the next greater element for each position from left to right.
Example 1
Input
5 2 1 3 5 4
Expected
3 3 5 -1 -1
Explanation
For 2 the next larger later value is 3; for 1 it is 3; for 3 it is 5; 5 has nothing larger after it, and 4 is last, so both give -1. Output: 3 3 5 -1 -1.
Example 2
Input
4 4 3 2 1
Expected
-1 -1 -1 -1
Explanation
The array strictly decreases, so no element has a greater value to its right and every answer is -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →