← DSA
MEDIUM

Daily Temperatures

PracticeNeetCode ↗LeetCode ↗

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

Example

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

Key Pointers

Step-by-Step Analysis

  1. Create an empty stack (holding indices) and a result array of zeros, same length as temperatures.
  2. For each index i, temperature t: while the stack isn't empty and t is warmer than the temperature at the stack's top index, pop that index and set result[popped] = i - popped.
  3. Push the current index i onto the stack.
  4. Any indices still on the stack after the loop never found a warmer day, so they stay 0 (the default).

Complexity

Time: O(n) — Space: O(n)

Code

def dailyTemperatures(temperatures: list[int]) -> list[int]:
    result = [0] * len(temperatures)
    stack = []

    for i, t in enumerate(temperatures):
        while stack and t > temperatures[stack[-1]]:
            prev_index = stack.pop()
            result[prev_index] = i - prev_index
        stack.append(i)

    return result

Code Explanation

How the solution above works, piece by piece.

  1. result starts as all 0 ("no warmer day"), and the stack holds indices of days still waiting for a warmer day.
  2. For each day i, pop every waiting day that is colder than today: today is their first warmer day, so their answer is i - prev_index.
  3. Then push today; it now waits too.
  4. The stack stays in decreasing temperature order (a monotonic stack), so each day is pushed once and popped at most once: O(n) total.
  5. Days never popped (76, 73) keep the default answer 0.

Visual Walkthrough

Running it on temperatures = [73, 74, 75, 71, 69, 72, 76, 73]:

trace730741752713694725766737i=073push7374757169727673i=174answers: [0]=17374757169727673i=275answers: [1]=17374757169727673i=37571push7374757169727673i=4757169push7374757169727673i=57572answers: [4]=1, [3]=27374757169727673i=676answers: [5]=1, [2]=47374757169727673i=77673push
Amber is today; blue marks the waiting days that today resolves. The right side shows the temperatures still on the stack, always decreasing. Final answer: [1, 1, 4, 2, 1, 1, 0, 0].
todayanswered now

Video Explanation

NeetCode — Daily Temperatures, LeetCode 739