Skip to content
DSA Patterns
Menu
Language
Monotonic StackLC #7395 of 6← PreviousNext →

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

Unverified
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

Next-greater-to-the-right, with the answer stored as the distance in days. The stack holds indices in decreasing temperature. When today is warmer than the top, answer[top] = i - top.

Reflection

  • When a warmer day arrives, each day on the stack gets i - idx. The stack stores the index, not the temperature.
  • An equal temperature is not warmer. Which day does > close that >= would leave open?
  • Whatever is left at the end is 0. A decreasing row is all 0s. An increasing row is 1 for every day.
Contributor review checklist

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
1/9

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

73
0
74
1
75
2
71
3
69
4
72
5
76
6
73
7
stack
∅
Stateans=[0,0,0,0,0,0,0,0]
Key:CurrentActive rangeMatchSettled