Next Greater Element I
easyStack & Queue+10 XPTime limit 2s
For a value x in array b, its next greater element is the first value to the right of x in b that is larger than x (or -1 if there is none). Array a is a subset of b; for every value of a, print its next greater element in b.
Input:
- line 1:
n1 n2 - line 2: the
n1values ofa - line 3: the
n2values ofb(all distinct)
Output: n1 numbers on one line.
Constraints: 1 ≤ n1 ≤ n2 ≤ 10⁵, 0 ≤ value ≤ 10⁵; every value of a appears in b.
Think about it: a monotonic stack answers "next greater" for every element of b in one O(n) pass — store the answers in a hash map, then look up each value of a.
Sample input 1
3 4 4 1 2 1 3 4 2
Sample output 1
-1 3 -1
Sample input 2
2 4 2 4 1 2 3 4
Sample output 2
3 -1
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).