#496

Next Greater Element I

Easy Monotonic stack

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

nums1 is a subset of nums2. For each value in nums1, find the first greater value to its right in nums2, or -1.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: for each value, the first bigger value to its right.

Why this works: keep a stack of values still waiting; a bigger value pops them all and becomes their answer.

Example: nums2 [1, 3, 4, 2]

1 waits, 3 answers 1, 4 answers 3, 2 waitsnext: 1→3, 3→4, 4→-1, 2→-1

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

For each element, scanning to the right — O(n²).

Solve on LeetCode ↗
Complexity
  • Time: O(n + m).
  • Space: O(n).
Topic: Stack & Queue
🎬 Episodes 46–52: video coming soon