Skip to content
ΣDSA Patterns
Menu
Language

Monotonic Stack

Guide 3 of 6 · Path 3 of 6

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 8
1
3
4
2
stack

nums1 queries later

nums2 = [1,3,4,2]. Build next-greater map with a decreasing stack.

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Next Greater Element I

Problem (restated)

nums1 is a subset of nums2. For each value x in nums1, find the first strictly greater element to the right of x in nums2. If none, answer is -1.

Intuition

Precompute next-greater for every value in nums2 with a decreasing monotonic stack, store results in a map, then look up each nums1 value.

Approaches

Monotonic stack on nums2 + map

Tested only
Time O(n + m)Space O(n)

Idea. Scan nums2 left to right. Stack holds values waiting for a greater successor. When x beats the top, map top → x. Unresolved values stay without an entry (answer -1).

Walkthrough. nums2 = [1,3,4,2], nums1 = [4,1,2] → next map: 1→3, 3→4 → answers [-1, 3, -1].

Trade-offs. Values in nums2 are unique, so a map keyed by value is safe. Index-based stack is equivalent when you need positions.

Solution
export function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
  const next = new Map<number, number>();
  const stack: number[] = [];
  for (const x of nums2) {
    while (stack.length && stack[stack.length - 1]! < x) {
      next.set(stack.pop()!, x);
    }
    stack.push(x);
  }
  return nums1.map((x) => next.get(x) ?? -1);
}
export function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
  const next = new Map<number, number>();
  const stack: number[] = [];
  for (const x of nums2) {
    while (stack.length && stack[stack.length - 1]! < x) {
      next.set(stack.pop()!, x);
    }
    stack.push(x);
  }
  return nums1.map((x) => next.get(x) ?? -1);
}

Template connection

Classic next-greater-to-the-right. Same stack discipline as Daily Temperatures; output is the greater value, not distance.

Reflection