progress

~/problems / Stacks / Monotonic stack

Daily Temperatures

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 daily_temperatures(temps: list[int]) -> list[int].

temps[i] is the temperature on day i. For each day, return how many days you have to wait for a strictly warmer day. Use 0 if no later day is warmer.

Example: [30, 38, 34, 31, 36, 40, 32] gives [1, 4, 2, 1, 1, 0, 0]. [50, 50, 50] gives [0, 0, 0] (equal isn't warmer).

Constraints: 1 <= len(temps) <= 10^5; temperatures are integers in [-100, 100].

⭐ Bonus: scanning forward from every day is O(n²) and still passes; a speed test earns a star in O(n).

Show hint

scan left to right and keep the days that are still waiting for a warmer day. When a new day arrives, which of the waiting days does it answer, and in what order do you find them?

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