Example 1
- Input
- nums1 = [4,1,2], nums2 = [1,3,4,2]
- Output
- [-1,3,-1]
4 has no greater element to its right in nums2. 1 is followed by 3. 2 sits at the end with nothing after it.
For each value in nums1, find that same value in nums2 and report the first larger value to its right, or -1 when none exists. A single decreasing stack over nums2 answers every query in linear time.
The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.
Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.
The answer is the first larger value by position, not the largest value in the suffix or the smallest larger value. Follow-up: solve in time, where m = nums1.length and n = nums2.length.
1 <= nums1.length <= nums2.length <= 10000 <= nums1[i], nums2[i] <= 10^4nums1 and nums2 are unique.nums1 also appear in nums2.4 has no greater element to its right in nums2. 1 is followed by 3. 2 sits at the end with nothing after it.
2 is followed by 3. 4 is the last element, so nothing greater follows it.
At the smallest valid size, the only value has no position to its right. Zero is an ordinary query value.
For 2 and 1, the first larger value encountered is 5. Although 3 is smaller than 5 and larger than either query, it occurs later and is not the answer. The maximum value 5 has no greater value to its right.
A value waits until the first larger value arrives to its right. In Example 1, 1 meets 3, then 3 meets 4; 4 and the final 2 never meet a larger value. Keep unresolved values in decreasing order on a stack: a new value can settle several smaller waiting values at once. Because all values are unique, a map keyed by value can later answer nums1 in its own order.
Reveal Scan Each Target: intuition, complexity, and code
2 in Example 1, always answers -1 since nothing follows it.-1.0 and 10000 are legal; a membership test must not confuse zero with an absent key.5 after [2,1]; keep popping until the decreasing order is restored.-1 default for values that stay on the stack, which drops the queries with no greater element.[2,1,5], arrival 5 settles both 1 and 2.[2,5,3] must give 5 for query 2.A monotonic stack resolves next-greater questions in one pass: smaller values wait on the stack until the arrival that settles them.