progress

~/problems / Stacks / Monotonic stack

Next Greater Element I

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

Write next_greater_element(nums1: list[int], nums2: list[int]) -> list[int].

nums2 has distinct values and contains every value of nums1. For each x in nums1, return the first value to the right of x in nums2 that is larger than x, or -1.

Example: nums1 = [6, 1, 8], nums2 = [1, 6, 2, 8] gives [8, 6, -1]. nums1 = [2], nums2 = [2, 1] gives [-1].

Constraints: 1 <= len(nums1) <= len(nums2) <= 10^5.

⭐ Bonus: a speed test earns a star in O(n) (searching nums2 per query is O(n²) but still passes).

Show hint

answer all of nums2 in one left-to-right pass with a stack of values still waiting, and store the answers in a dict.

Topic: Monotonic stack. Next greater/smaller element in O(n); histogram rectangles; trapping water.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc