For each element in a subset array, find the first greater value that appears to its right in a larger array.
Problem
You are given two integer arrays, nums1 and nums2, where every value in nums1 appears in nums2 and both arrays contain distinct values.
For each element x in nums1, find the next greater element of x in nums2 — the first number strictly larger than x that appears to the right of x in nums2.
Return an array ans such that ans[i] is the next greater element of nums1[i]. If no greater element exists to the right, use -1.
Notes
- The next greater element is searched only in
nums2. - Each query in
nums1should be answered based on its position innums2. - Values are distinct, so each number can be matched unambiguously.
Input Format
- Two integer arrays
nums1andnums2 nums1is a subset ofnums2- All values are distinct
Output Format
- Return an integer array
ans ans[i]is the next greater element ofnums1[i]innums2, or-1if none exists
Constraints
1 <= nums1.length <= nums2.length1 <= nums2.length- Elements are distinct
- Every element of
nums1appears innums2
Example 1
Input
nums1 = [4,1,2] nums2 = [1,3,4,2]
Output
[-1,3,-1]
Explanation
- For
4, there is no greater number to its right innums2. - For
1, the next greater number to its right is3. - For
2, there is no greater number to its right.
Example 2
Input
nums1 = [2,4] nums2 = [1,2,3,4]
Output
[3,-1]
Explanation
- For
2, the first greater value to its right is3. - For
4, nothing greater appears after it, so the answer is-1.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.