Problem 717
Next Greater Element II
Medium · 20 pts · Array, Monotonic Stack
Problem
The array is circular: after the last element, the search continues from the first one. For every element, find the first larger element when walking forward around the circle, and print -1 if there is none. Scan the array twice from right to left, keeping a stack of candidates in decreasing order; pop everything not larger than the current value, and the top of the stack is the answer.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].
Output
Print N integers separated by spaces: the next greater element of each element, or -1.
Constraints
1 <= N <= 100000; -10^9 <= A[i] <= 10^9
Example input
3 1 2 1
Example output
2 -1 2
Explanation
For 1 2 1, the first 1 sees 2 next, and 2 has nothing larger anywhere, so -1. The last 1 wraps around to the start and finds 2. The answer is 2 -1 2.