Next Greater Element I
1 approach, code in every language
Problem description
You are given two arrays, `nums1` and `nums2`, where every element of `nums1` also appears somewhere in `nums2` and all values are distinct. `nums1` is a subset of `nums2`.
For each value `x` taken from `nums1`, locate it inside `nums2` and look at the elements that come after it. The next greater element of `x` is the first value to its right in `nums2` that is strictly larger than `x`. If no such value exists, the answer for that query is `-1`.
Return an array `answer` of the same length as `nums1`, where `answer[i]` is the next greater element for `nums1[i]`.
Example 1
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
For 4 there is nothing larger to its right, so -1. For 1 the next larger value is 3. For 2 nothing larger follows, so -1.
Example 2
Input: nums1 = [2,4], nums2 = [1,2,3,4]
Output: [3,-1]
For 2 the next larger value is 3. For 4 there is no larger value to the right, so -1.
Constraints
1 <= nums1.length <= nums2.length <= 10000 <= nums1[i], nums2[i] <= 10^4All integers in nums1 and nums2 are unique.All integers of nums1 also appear in nums2.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Auction Watchlist Highs is our own problem on the technique behind Next Greater Element I: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free