Algorithms · Stacks
Daily Temperatures
For each day, how long until a warmer one?
The problem
For each day in temps, return how many days you’d wait for a warmer day (0 if it never comes).
wait_for_warmer([73, 74, 75, 71, 69, 72, 76, 73])→[1, 1, 4, 2, 1, 1, 0, 0]wait_for_warmer([30, 40, 50, 60])→[1, 1, 1, 0]Start with the way that works
This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.
def wait_for_warmer(temps):take a temperature for each day answer = []days to wait, one per day for i in range(len(temps)):for each day wait = 0assume no warmer day comes for j in range(i + 1, len(temps)):look at the days after it if temps[j] > temps[i]:warmer? wait = j - ithat's how long we'd wait breakstop looking answer.append(wait)record it return answerone wait per dayNow ask: what if there were a billion?
This “waiting line on a stack” is called a monotonic stack. Each day goes on the stack once and comes off once, so even 10 years of hourly readings take one quick pass.
Aim for O(n)🔥 boss
Think it through
It gets colder five days in a row. How many of those days are still waiting for a warmer day?
- Just the last one
- All five
Show the answer
All five. They’re all waiting, and they wait in order: the coldest most recent on top. A warm day can settle several of them at once.
A warm day arrives. Which waiting days does it settle?
- Only yesterday
- Every waiting day colder than it, from the most recent back
Show the answer
Every waiting day colder than it, from the most recent back. Pop while the top is colder: each day is pushed once and popped once, so it’s one pass overall. A monotonic stack: a stack that stays in order.
Stuck? 3 nudges, smallest first
- When it keeps getting colder, every day is still waiting, and the obvious way rescans the whole future for each of them.
- Keep the days that are still waiting on a stack. A warm day can finish off several of them at once.
- For each day
i: while the top waiting day is colder than today, pop it and set its answer toi - j. Then pushi.
The fast way
Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.
Show the fast version
def wait_for_warmer(temps):take a temperature for each day answer = [0] * len(temps)assume nobody gets a warmer day waiting = []days still waiting for a warmer one (a stack) for i, t in enumerate(temps):walk through the days once while waiting and temps[waiting[-1]] < t:today beats the most recent waiting day? j = waiting.pop()that day's wait is over answer[j] = i - jit waited this many days waiting.append(i)today starts waiting too return answerone wait per daySolve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.