← Whiteboard questions

Daily Temperatures

Find how many days until a warmer one

DSA, Medium, Stack

Which structure or algorithm, and what does it cost.

A list temps holds the temperature of each day, in order. For every day, count how many days you must wait until a strictly warmer day arrives. If no later day is warmer, the count for that day is 0. Return the list of counts, one per day, in the same order as temps.

Examples

Input temps = [21, 25, 19, 20, 30, 18]
Output [1, 3, 1, 1, 0, 0]
Why the second day (25) waits three days for the 30. The last two days have no warmer day after them.
Input temps = [30, 30, 30]
Output [0, 0, 0]
Why equal is not warmer, so no day ever waits for a warmer one.
Input temps = [10, 20, 30, 40]
Output [1, 1, 1, 0]
Why each day is followed at once by a warmer day, except the last.

Constraints

Your answer must contain

Target Aim for O(n) time and O(n) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

For one day, you scan forward until you see a warmer day. Think about which days make that scan repeat work.

Hint 2 the approach

Keep the days that still wait for a warmer day in a pile. When a new day arrives, which waiting days does it answer?

Hint 3 the key step

Keep a stack of positions of days that still wait. Which end holds the days a new day can answer? When do you stop? The wait is a position gap.

Walkthrough

Full walkthrough brute force to best

Brute force

For each day, scan forward until you find a warmer day and count the steps. Each scan can run to the end of the list. That is O(n^2) time and O(1) extra memory. A run of falling temperatures is the worst case, with about 5 billion steps for 100,000 days.

Better method

Go from the right. For day i, start at day i + 1 and jump ahead by the stored counts. If day j is not warmer, the next candidate is day j plus its count, because day j already knows where its next warmer day is. Stop at a warmer day, or when a count is 0 (no warmer day exists). This skips many days, but it is harder to reason about than the stack. It is O(n) time in total and needs no stack, only the answer list.

Best method

Keep a stack of days that still wait for a warmer day. Their temperatures never rise from the bottom of the stack to the top, because a warmer day would already have answered the one below it. Walk the days in order. For day i, while the top waiting day is cooler than day i, pop it. Its wait is i minus its position. Then push day i. Each day is pushed once and popped at most once, so the total work is linear. Days left on the stack at the end keep the count 0. The same shape, a stack that stays ordered, fits any question about the next larger or smaller item.

Hand trace

Run on [21, 25, 19, 20, 30, 18]. Day 0 (21): the stack is empty, so push it. Stack [0]. Day 1 (25): 21 is cooler, so pop day 0 with wait 1, then push day 1. Stack [1]. Day 2 (19): 25 is not cooler, so push. Stack [1, 2]. Day 3 (20): 19 is cooler, so pop day 2 with wait 1. 25 is not cooler, so push. Stack [1, 3]. Day 4 (30): pop day 3 with wait 1, then pop day 1 with wait 3, then push. Stack [4]. Day 5 (18): 30 is not cooler, so push. Stack [4, 5]. Days 4 and 5 keep 0. The result is [1, 3, 1, 1, 0, 0].

Code

def daily_temperatures(temps):
    answer = [0] * len(temps)
    stack = []                      # positions of days still waiting
    for i, t in enumerate(temps):
        while stack and temps[stack[-1]] < t:
            j = stack.pop()
            answer[j] = i - j
        stack.append(i)
    return answer

Time and memory

O(n) time, because each day is pushed once and popped at most once. O(n) memory, because the stack can hold every day, for example when temperatures only fall.

Common mistakes

  • Pushing temperatures instead of positions. The answer needs the gap in positions.
  • Popping when the top is cooler or equal. Equal is not warmer, so pop only when strictly cooler. With [30, 30, 30] every count must stay 0.
  • Filling in a value for the days left on the stack. They have no warmer day, so they keep 0.

Related problems

More Stack problems
Daily Temperatures: hints, walkthrough and Python solution