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 one larger than 3. Only 2 follows the 8, so 8 gets -1. The value right after 1 is 6, which is already larger.

lock icon+14 hidden tests on Submit

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 cases

Case 1

Case 2

Case 3

Input

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

Expected

[8, -1, 6]