DSA Factory
Free Stacks and queues lessonsStacks and queues · Stage 2 · Monotonic stack · Step 2

Days until a warmer one

For each day, count how many days you must wait for a warmer temperature, by keeping the days still waiting on a stack and answering them with distances. About 14 minutes.

Answer with a distance

This is the previous step with a different answer. For each day you want the number of days until a warmer one. When a warmer day i arrives and pops a waiting day j, the wait is the number of days between them, which is i minus j.

So the stack stores positions of days, not temperatures. The temperature of a waiting day is looked up from its position when needed.

Pop day j: when day i is warmer.
Wait: is i minus j days.
In code
while stack and temps[stack[-1]] < t:
    j = stack.pop()
    res[j] = i - j
Temperatures over 8 days: 73, 74, 75, 71, 69, 72, 76, 73.
73
0
74
1
75
2
71
3
69
4
72
5
76
6
73
7
i

Day 1 is 74, warmer than waiting day 0 (73). Day 0 waits 1 day. Day 1 now waits.

Move 1 of 6

Never warmer means zero

A day with no warmer day after it is never popped. The problem asks for 0 in that case, so fill the answers with zeros first, and the days left on the stack at the end are already right.

The equal case matters too. A day that is only as warm as a waiting day does not answer it, since the wait is until a warmer day. Compare strictly.

Fill with zeros: so unanswered days are right.
Strictly warmer: equal is not enough.
In code
res = [0] * len(temps)
stack = []
Quick check

Day 3 is warmer than waiting day 1. How many days does day 1 wait?

  1. A2
  2. B3
  3. C1
Show the answer

2. The distance is 3 minus 1.

Your problem

Daily temperatures

Given an array temperatures of daily temperatures, return an array answer where answer[i] is the number of days you have to wait after day i to get a warmer temperature. If there is no future day with a warmer temperature, answer[i] is 0.

Example
temperatures = [73, 74, 75, 71, 69, 72, 76, 73] → [1, 1, 4, 2, 1, 1, 0, 0]

1 ≤ length of temperatures ≤ 100,000 · 30 ≤ temperatures[i] ≤ 100

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve