Next Greater Element I

The next greater element of a value in an array is the first value to its right that is larger. You are given two arrays of distinct integers, `nums1` and `nums2`, where `nums1` is a subset of `nums2`. For each `nums1[i]`, find the same value in `nums2` and return its next greater element there, or `-1` if there is none.

30:00

Next Greater Element I
easy
Free written solution
Topics
Companies

The next greater element of a value in an array is the first value to its right that is larger. You are given two arrays of distinct integers, nums1 and nums2, where nums1 is a subset of nums2. For each nums1[i], find the same value in nums2 and return its next greater element there, or -1 if there is none.

Example 1:
Input: {"nums1":[4,1,2],"nums2":[1,3,4,2]}
Output: [-1,3,-1]
Constraints:
  • 1≤nums1.length≤nums2.length≤10001 \leq \text{nums1.length} \leq \text{nums2.length} \leq 1000

  • 0≤nums1[i],nums2[i]≤1040 \leq \text{nums1}[i], \text{nums2}[i] \leq 10^4

  • All integers in nums1 and nums2 are unique.

  • All the integers of nums1 also appear in nums2.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums1":[4,1,2],"nums2":[1,3,4,2]}

nums2, scanned left to right (below each value: its next greater element)

1
3
4
2

Scan nums2 once, keeping a stack of values that have not met a larger value yet. Then answer the 3 queries from nums1 with lookups.

waiting stack (decreasing, top first)

empty

next_greater map (0 entries)

no entries yet

nums1 queries → ans

4
?
1
?
2
?
Variables
VariableValue
stack[]
found0
DepthFunction Call
Stack empty
0/15