Skip to content
ΣDSA Patterns
Menu
Language

Monotonic Stack

Guide 5 of 6 · Path 5 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 9
73
74
75
71
69
72
76
73
stack

Next warmer day. Stack keeps decreasing temperatures (by index).

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

Daily Temperatures

Problem (restated)

Given daily temperatures, return an array answer where answer[i] is the number of days you wait after day i for a warmer temperature. If none, answer[i]=0.

Intuition

Next greater element → monotonic decreasing stack of indices. When a warmer day appears, pop and record distance.

Approaches

Monotonic decreasing stack

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

Idea. Stack holds indices with decreasing temps. For each day, while stack top is cooler, pop and set answer.

Walkthrough. [73,74,75,71,69,72,76,73] → [1,1,4,2,1,1,0,0].

Trade-offs. Linear vs O(n²) nested scan. Stack stores indices not values.

Solution
export function dailyTemperatures(temperatures: number[]): number[] {
  const n = temperatures.length;
  const ans = new Array<number>(n).fill(0);
  const stack: number[] = [];
  for (let i = 0; i < n; i++) {
    while (stack.length && temperatures[i]! > temperatures[stack[stack.length - 1]!]!) {
      const j = stack.pop()!;
      ans[j] = i - j;
    }
    stack.push(i);
  }
  return ans;
}
export function dailyTemperatures(temperatures: number[]): number[] {
  const n = temperatures.length;
  const ans = new Array<number>(n).fill(0);
  const stack: number[] = [];
  for (let i = 0; i < n; i++) {
    while (stack.length && temperatures[i]! > temperatures[stack[stack.length - 1]!]!) {
      const j = stack.pop()!;
      ans[j] = i - j;
    }
    stack.push(i);
  }
  return ans;
}

Template connection

Monotonic stack next-greater template.

Reflection