← Practice
📖 Monotonic stackLearning path
Browsing as guest·Sign in or create a free account to save progress and use tutor tools.
Lesson·difficulty 4/5·~25 min

Monotonic stack: daily temperatures

You've got a week's worth of daily temperatures and one nagging question for each day: how many days until it gets warmer? For every day i, return the number of days you have to wait for a strictly warmer temperature. If no warmer day ever comes, the answer is 0.

The brute-force urge is to scan forward from each day — that's O(n²). The slick trick is a monotonic stack: a stack that only ever holds indices of days still waiting for a warmer day, kept in decreasing temperature order.

Walk left to right. When today's temperature is warmer than the day sitting on top of the stack, that older day's wait is over — pop it and record the gap (today's index minus its index). Keep popping while today beats the top, then push today on to wait its turn.

In plain steps (you write the Python):

text
start the answer as all zeros; keep an empty stack of waiting day-indices
walk index i over the days:
    while the day on top of the stack is colder than today:
        pop it — its wait ends now; record (i - that day's index)
    push i onto the stack
days still on the stack at the end never warmed up, so they keep their 0

Each index is pushed once and popped at most once, so the whole thing is O(n). Anything left on the stack at the end never warmed up, so it keeps its 0.

Your task

Write daily_temperatures(temps) that returns a list where result[i] is the number of days until a warmer temperature, or 0 if there is none.

python
daily_temperatures([73,74,75,71,69,72,76,73])  # [1, 1, 4, 2, 1, 1, 0, 0]
daily_temperatures([30,40,50,60])              # [1, 1, 1, 0]
daily_temperatures([30,60,90])                 # [1, 1, 0]
daily_temperatures([50])                       # [0]

Hint: initialise the answer to all zeros, then a monotonic stack only ever fills in the days that actually find a warmer future.

Tests

  • week of weather
  • steadily warming
  • always next day
  • single day

✦ Stuck? Ask for a spark

Sign in or create a free account to use your monthly AI explainer allowance.

warming up
Loading editor…
Consolewaiting

$ Console output will appear here.

>_AI coach
Sign in or create a free account to chat with the tutor.