Skip to content

Next Greater Element I

EasyStack
Decode it first. Clues, constraints, pattern and plan before any code.

You get two lists of distinct integers, nums1 and nums2, where every value in nums1 also appears somewhere in nums2.

For each value x in nums1, find where x sits in nums2 and look to its right: the answer is the first value to the right of x in nums2 that is greater than x, or -1 if there is none. Return the answers in the order of nums1.

nums1 = [4, 1, 2], nums2 = [1, 3, 4, 2]  →  [-1, 3, -1]
nums1 = [2, 4],    nums2 = [1, 2, 3, 4]  →  [3, -1]

Constraints

  • 1 <= nums1.length <= nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 10^4
  • All values in each list are unique, and every value of nums1 is in nums2.
  • Aim for O(nums1.length + nums2.length).