Skip to content
Problem 496 · LeetCode 496(opens in a new tab)

Next Greater Element I

EasyArrays

For a value in a list, its next greater element is the first value to its right that is bigger than it. If no value to its right is bigger, the answer is −1.

You get two lists of distinct numbers, nums1 and nums2. Every number in nums1 also appears somewhere in nums2. For each number in nums1, find it in nums2 and report its next greater element there. Return the answers in the order of nums1.

Example 1

Input:  nums1 = [2, 4, 8], nums2 = [5, 2, 7, 4, 8]
Output: [7, 8, -1]
Why:    after 2 comes 7; after 4 comes 8; nothing follows 8
2 more examples and the constraints

Example 2

Input:  nums1 = [6, 3], nums2 = [9, 6, 3]
Output: [-1, -1]
Why:    nums2 only falls, so nothing to the right is bigger

Example 3

Input:  nums1 = [1, 5], nums2 = [1, 3, 5, 7]
Output: [3, 7]
Why:    in a rising list the answer is the very next value

Constraints

  • 1 ≤ length of nums1 ≤ length of nums2 ≤ 1,000
  • 0 ≤ every value ≤ 10,000
  • No value repeats within a list, and every value of nums1 is in nums2

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Scan right for each queryO(m·n)
  2. Monotonic stackO(m + n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 queries on 1,000 valuesVerdict
Scan right for each queryO(m·n)
Fine here; misses the follow-up
Monotonic stackO(m + n)
Best; one pass and lookups

m = length of nums1, n = length of nums2.

Edge cases to test

  • Last value of nums2. Nothing is to its right, so its answer is always −1.
  • Falling list. [9, 6, 3]: every value stays on the stack and every answer is −1.
  • Answer far away. In [8, 6, 4, 2, 10] the first bigger value after 8 is the last one.
  • One value. nums1 = [0], nums2 = [0] gives [−1].

Common mistakes

  • Returning the largest value to the right instead of the first bigger one.
  • Searching from the start of nums2 instead of from the query's own position.
  • Popping while the top is bigger, which builds a rising stack and answers the wrong question.

How to talk through it

  1. 1Clarify. Values are distinct? Bigger means strictly bigger? Which list do I answer for?
  2. 2Give the brute force. For each query, find it and scan right: O(m·n). Say it rereads the same values.
  3. 3Name the pattern. "First bigger value to the right" is the classic monotonic stack. Answer all of nums2 once.
  4. 4Code the stack and the map. Pop while the top is smaller, record the answer, then push.
  5. 5Test out loud. Run the falling list and the last value before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?