İçeriğe atla
ΣDSA Patterns
Menü
Dil

Monoton Yığın

Rehber 3 / 6 · Yol 3 / 6

Interactive

Zihinsel model

Bu problem için animasyonlu çözüm. Adımları kaydır veya boşlukla duraklat; değişmezi yüksek sesle yeniden anlat.

Adım 1 / 8
1
3
4
2
stack

nums1 queries later

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

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

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