Monotonic Stack

Next Greater Element I

Easy
Solve it on LeetCode ↗

The problem

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

Stuck? Reveal hints one at a time

How to approach it

  1. 1Scan nums2 keeping a stack of values with no answer yet (decreasing).
  2. 2When value v arrives, pop everything smaller — v is their next-greater; record in a map.
  3. 3Push v. Unpopped values map to −1 by default.
  4. 4Map nums1 through the lookup.

Key insight

Solve the harder full-array problem once, and the actual query set becomes trivial — a common inversion worth recognizing.

The solution

Watch out for

  • Values are distinct here — that is what lets values (not indices) key the map.
  • The circular follow-up (Next Greater Element II) iterates indices 0..2n−1 with mod.