Skip to content

Daily Temperatures

For each day, count the days until a warmer one, using a stack of days that are still waiting.

MediumStacks
Solve on LeetCode

The problem

You get an array temperatures with one temperature per day. For each day, find how many days you have to wait until a day that is strictly warmer. Return an array of those waits, with 0 for a day that is never followed by a warmer one.

Input temperatures = [31, 29, 33, 30, 30, 35]

Output [2, 1, 3, 2, 1, 0]

Day 0 (31) waits 2 days for 33. Day 3 (30) skips the equal day 4 and waits 2 days for 35.

Input temperatures = [40, 38, 36]

Output [0, 0, 0]

Every day is cooler than the one before it, so no day is ever followed by a warmer one.

Key constraint: Up to 100,000 days, so checking every pair of days (about 5 billion checks) is far too slow.

How to spot the pattern

  • For each element you need the next element to its right that is larger.
  • The answer is a distance (how many steps ahead), so you need positions, not just values.
  • The input is large enough that O(n^2) won't pass.

The idea

Keep a stack of the days that are still waiting for a warmer day. From the bottom of the stack to the top their temperatures never rise, because a warmer day would already have answered the cooler days before it. When today is warmer than the day on top, today is that day's answer, so pop it and write how many days passed; repeat until the top is not cooler, then push today.

Brute force: For each day, scan forward until a warmer day appears, which takes O(n^2) time in the worst case.

Step by step

  1. 1Fill the answer array with 0s and start with an empty stack of day indexes.
  2. 2For each day i, while the stack is not empty and the day on top is cooler than day i, pop that index j and set answer[j] = i - j.
  3. 3Push i onto the stack, since it now waits for its own warmer day.
  4. 4Days still on the stack at the end keep their 0.

See the pattern move

The stacks pattern on a small example. Step through it, or press play.

Code

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        answer = [0] * len(temperatures)
        waiting = []  # indexes of days without a warmer day yet
        for i, temp in enumerate(temperatures):
            while waiting and temperatures[waiting[-1]] < temp:
                j = waiting.pop()
                answer[j] = i - j
            waiting.append(i)
        return answer

Complexity

Time

O(n)

Space

O(n)

The inner while loop looks like nested work, but each index is pushed once and popped at most once, so the whole run does O(n) work.

Watch out for

  • Pushing temperatures instead of indexes: you need the index to know how many days passed.
  • Popping when the temperatures are equal: a day with the same temperature is not warmer, so the comparison must be strict.
  • Calling the solution O(n^2) because of the nested loop; count pops instead, and there are at most n of them.

Follow-up questions

Can you do it without a stack?

Go from right to left and, for each day, jump forward through answers you already know (j += answer[j]) until you reach a warmer day or a day with answer 0. It needs no extra space besides the output and still runs in linear time.

How would you find the most recent warmer day before each day?

Walk from left to right with the same kind of stack, but pop every day that is not warmer than today first; the index left on top, if any, is the previous warmer day. Then push today.

In Hinglish

Jo din abhi garam din ka intezaar kar rahe hain, unke index stack mein rakho. Aaj zyada garam hai toh aaj hi unka jawab hai: pop karo aur dino ka gap likh do.

Related problems