Menu
CoddyTech

Next Greater Element I

You get two arrays of distinct integers, nums1 and nums2, and every value of nums1 also appears in nums2. The next greater element of a value x is the first value to the right of x in nums2 that is larger than x, or -1 if no such value exists.

Return an array holding the next greater element of each value of nums1, in the order of nums1.

Function

nextGreaterElement(nums1: integer-array, nums2: integer-array) → integer-array
nums1integer-array
the values to answer, all of them found in nums2
nums2integer-array
the array in which you look to the right of each value
Returnsinteger-array
the next greater element of each value of nums1, or -1, in the order of nums1

Constraints

  • 1 ≤ nums1.length ≤ nums2.length ≤ 104
  • 0 ≤ nums1[i], nums2[i] ≤ 104
  • All values in nums1 are distinct, and all values in nums2 are distinct.
  • Every value of nums1 appears in nums2.

Examples

Input
nums1 = [3, 8, 1]nums2 = [1, 6, 3, 8, 2]
Output
[8, -1, 6]
Explanation
After the 3 in nums2 come 8 and 2, and 8 is the first larger one. Only 2 follows the 8, so 8 gets -1. Right after 1 comes 6, already larger.
challenge icon

Follow-up

For every position of nums2, can you return how many steps to the right its next greater element sits, with the same single pass?

Reset code
def nextGreaterElement(nums1, nums2):
    # Write code here

Test #1

Test #2

Test #3

Arguments

nums1 = [3, 8, 1]
nums2 = [1, 6, 3, 8, 2]

Expected Output

[8, -1, 6]