EasyArrayHash TableStackMonotonic Stack

Next Greater Element I

LeetCode
1 approach, code in all languages

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 <= 1000
  • 0 <= nums1[i], nums2[i] <= 10^4
  • All integers in nums1 and nums2 are unique.
  • All integers of nums1 also appear in nums2.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now