Days Until a Higher Temperature

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

You are given an integer list temps where temps[i] records the midday temperature on day i (0-indexed). Build and return an integer list answer of the same length where answer[i] gives the minimum positive number of days (j - i) after day i until a day j > i has a strictly higher temperature (temps[j] > temps[i]).

If no subsequent day is strictly hotter than day i (including when later days only tie temps[i]), set answer[i] to 0.

def daily_temperatures(temps: List[int]) -> List[int]:

Examples

Example 1

  • Input: temps = [64, 68, 65, 65, 63, 70, 67]
  • Output: [1, 4, 3, 2, 1, 0, 0]
  • Walk-through:
    • Day 0 (64): day 1 reaches 68, which is 1 - 0 = 1 day later.
    • Day 1 (68): days 2, 3, and 4 stay below 68; day 5 hits 70, giving 5 - 1 = 4.
    • Day 2 (65): day 3 ties at 65 (not strictly hotter), so both day 2 and day 3 wait until day 5 (70), giving 3 and 2 days respectively.
    • Day 4 (63): day 5 (70) is 1 day away.
    • Days 5 (70) and 6 (67): no later day exceeds either reading, so both entries are 0.

Example 2

  • Input: temps = [42, 47, 53, 59, 65]
  • Output: [1, 1, 1, 1, 0]
  • Walk-through: Every day except the final day is immediately followed by a hotter reading one day later, while day 4 (65) has no future days and receives 0.

Example 3

  • Input: temps = [88, 82, 82, 75]
  • Output: [0, 0, 0, 0]
  • Walk-through: Readings never rise above any earlier day's value, so every entry remains 0.

Constraints

  • 1 <= len(temps) <= 10^5 (if temps is empty, return [])
  • 30 <= temps[i] <= 100

Step-by-step walkthrough

  1. Restate the goal and input rules

    Given a list temps where temps[i] is the temperature reading on day i, we must return a list answer of the same length where answer[i] is how many days pass (j - i) until the earliest later day j > i with temps[j] > temps[i].

    Three rules govern every case:

    • Strictly hotter (>): a later day with the exact same reading (65 after 65) does not qualify; we keep waiting.
    • No hotter future day: if no later day exceeds temps[i] (which always holds for the last day), answer[i] stays 0.
    • Scale: temps can contain up to 10^5 entries, so our solution must run in O(n) time rather than O(n^2).
  2. Start with brute force and see why it repeats work

    A direct baseline stands on each day i and scans rightward (j = i + 1, i + 2, ...) until finding a reading above temps[i]:

    def daily_temperatures_brute(temps):
        answer = [0] * len(temps)
        for i in range(len(temps)):
            for j in range(i + 1, len(temps)):
                if temps[j] > temps[i]:
                    answer[i] = j - i
                    break
        return answer
    

    Why does this time out on large inputs? Picture 99,999 days at 65 degrees followed by one final day at 66 degrees. Day 0 checks 99,999 future days, day 1 checks 99,998 days, and so on — roughly 5 * 10^9 comparisons in total (O(n^2)).

    Instead of sending every cool day forward on its own search, we can park unresolved days in a waiting stack and let a hot day resolve all cooler waiting days at once when we reach it.

  3. Key idea: keep unresolved days in a monotonic stack

    As we sweep left to right (today = 0, 1, ..., n - 1), we maintain a stack waiting_days storing the indices of earlier days that still lack a hotter successor.

    When today arrives with reading today_temp:

    1. While waiting_days is non-empty and the index on top (waiting_days[-1]) has a reading strictly below today_temp, pop prev_day = waiting_days.pop() and set answer[prev_day] = today - prev_day.
    2. Append today to waiting_days so it waits for a hotter day of its own.

    Why is checking the top of waiting_days sufficient? Because temperatures along waiting_days never rise from bottom to top! Whenever a warmer reading arrives, it pops every strictly cooler day before pushing itself, keeping the coolest unresolved day at waiting_days[-1]:

    Suppose days 1(68), 2(65), and 4(63) are waiting, and day 5 arrives with temp 67:
    
      Stack before day 5 (bottom -> top):   [ 1(68), 2(65), 4(63) ]   <-- temps: 68 >= 65 >= 63
                                                            ^^^^^
      1. Top is 4(63) < 67  --> pop day 4, answer[4] = 5 - 4 = 1
      2. Top is 2(65) < 67  --> pop day 2, answer[2] = 5 - 2 = 3
      3. Top is 1(68) >= 67 --> STOP! Since 68 >= 67, everything deeper is also >= 68.
      4. Push 5(67).
    
      Stack after day 5 (bottom -> top):    [ 1(68), 5(67) ]          <-- still non-increasing!
    
  4. Write the single-pass stack loop

    Two small choices keep the implementation concise:

    • Push day indices rather than temperatures: an index prev_day gives both the elapsed gap today - prev_day and the stored temperature temps[prev_day].
    • Initialize answer to all 0s: any index still sitting in waiting_days when the loop finishes never saw a hotter day, so its 0 default is already final.
    from typing import List
    
    
    def daily_temperatures(temps: List[int]) -> List[int]:
        num_days = len(temps)
        # answer[i]: days after day i until the first strictly warmer day (defaults to 0 if none).
        answer = [0] * num_days
        # waiting_days: monotonic stack of day indices [d0, d1, ...] still waiting for a warmer day;
        # temperatures never increase from bottom to top, so the coldest waiting day is always on top.
        waiting_days: List[int] = []
    
        for today, today_temp in enumerate(temps):
            # Strict '<' because an equal temperature does NOT count as warmer.
            while waiting_days and temps[waiting_days[-1]] < today_temp:
                prev_day = waiting_days.pop()
                answer[prev_day] = today - prev_day
    
            # Today now waits for a future day strictly warmer than today_temp.
            waiting_days.append(today)
    
        return answer
    
  5. Trace Example 1 and verify O(n) time

    Let's trace Example 1, temps = [64, 68, 65, 65, 63, 70, 67], writing stack entries as idx(temp) from bottom to top:

    today | temp | popped & resolved                                   | waiting_days after
    ------+------+-----------------------------------------------------+----------------------------------
      0   |  64  | -                                                   | [0(64)]
      1   |  68  | pop 0 -> answer[0] = 1 - 0 = 1                      | [1(68)]
      2   |  65  | - (68 is not < 65)                                  | [1(68), 2(65)]
      3   |  65  | - (65 is not < 65; ties keep waiting)               | [1(68), 2(65), 3(65)]
      4   |  63  | - (65 is not < 63)                                  | [1(68), 2(65), 3(65), 4(63)]
      5   |  70  | pop 4->1; pop 3->2; pop 2->3; pop 1->4              | [5(70)]
      6   |  67  | - (70 is not < 67)                                  | [5(70), 6(67)]
    
    End of list: days 5 and 6 remain on stack -> keep 0.
    Final answer: [1, 4, 3, 2, 1, 0, 0]
    

    Why is a while loop nested inside a for loop still O(n)? Count stack actions over the entire call: each of the n indices is pushed onto waiting_days once and popped at most once, bounding total while iterations across all days combined by n.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def daily_temperatures(temps: List[int]) -> List[int]:
        num_days = len(temps)
        # answer[i]: days after day i until the first strictly warmer day (defaults to 0 if none).
        answer = [0] * num_days
        # waiting_days: monotonic stack of day indices [d0, d1, ...] still waiting for a warmer day;
        # temperatures never increase from bottom to top, so the coldest waiting day is always on top.
        waiting_days: List[int] = []
    
        for today, today_temp in enumerate(temps):
            # Strict '<' because an equal temperature does NOT count as warmer.
            while waiting_days and temps[waiting_days[-1]] < today_temp:
                prev_day = waiting_days.pop()
                answer[prev_day] = today - prev_day
    
            # Today now waits for a future day strictly warmer than today_temp.
            waiting_days.append(today)
    
        return answer
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a clipboard of open tickets: each morning you write today's day index and temperature on a ticket, check whether today is hotter than the ticket sitting on top of the clipboard, close and pull off every cooler ticket that today beats, and finally clip today's ticket on top. That clipboard is a monotonic stack (a stack whose elements stay ordered in one direction from bottom to top — here non-increasing in temperature — because each incoming element pops anything that would break that order). Since cooler tickets never sit beneath warmer ones, the coolest unresolved day is always exposed on top in O(1) time.

Why does a naive double loop fall short? Scanning rightward from each day i to find its next hotter day j walks across the same flat or cooling stretches repeatedly. On 99,999 consecutive 65-degree days followed by a single 66-degree day, every starting index scans all the way to the end, costing roughly 5 billion comparisons (O(n^2)). Holding unresolved indices on a stack flips the work around so that single 66-degree day resolves all 99,999 waiting days in one linear sweep.

Here is a 5-day trace on temps = [68, 65, 63, 66, 70]:

Day 0 (68): stack empty               -> push 0(68)          stack: [0(68)]
Day 1 (65): 68 is not < 65            -> push 1(65)          stack: [0(68), 1(65)]
Day 2 (63): 65 is not < 63            -> push 2(63)          stack: [0(68), 1(65), 2(63)]
Day 3 (66): pop 2(63) -> ans[2]=3-2=1
            pop 1(65) -> ans[1]=3-1=2
            stop at 0(68) >= 66       -> push 3(66)          stack: [0(68), 3(66)]
Day 4 (70): pop 3(66) -> ans[3]=4-3=1
            pop 0(68) -> ans[0]=4-0=4 -> push 4(70)          stack: [4(70)]

Day 4 stays on the stack -> ans[4] = 0.  Result: [4, 2, 1, 1, 0]

Complexity

Let n = len(temps) be the number of days.

  • Time: O(n) (amortized O(1) per day, meaning the average work per day across the whole pass is constant even if an occasional hot spike pops many entries at once). Each index 0 .. n - 1 is pushed onto waiting_days once and popped at most once, so the outer for loop and inner while loop perform at most 2n stack operations combined.
  • Space: O(n). The output list answer holds n integers, and in the worst case (when readings never rise, such as [88, 82, 75] or [65, 65, 65]) waiting_days holds all n indices at once.

Edge cases

  • Empty input ([]) or single day ([50]): Returns [] and [0] cleanly without extra if branches.
  • All equal readings ([65, 65, 65]): Because < is strict, no 65 pops an earlier 65, leaving [0, 0, 0].
  • Tied readings resolved together ([65, 65, 70]): Both 65s remain on the stack until 70 pops both, yielding [2, 1, 0].
  • Non-increasing readings ([88, 82, 82, 75], Example 3): Every index stays on the stack, returning [0, 0, 0, 0].
  • Cooling run followed by one spike ([80, 60, 50, 40, 90]): Day 4 (90) drains the entire stack in one while loop, returning [4, 3, 2, 1, 0].
  • Boundary readings (30 and 100): Nothing exceeds 100, so any day at 100 always ends with 0 even if another 100 appears later.

Common mistakes

  • Writing <= instead of < in the while test: That treats a tie as hotter, turning [65, 65] into [1, 0] instead of [0, 0].
  • Pushing temperatures (temps[today]) instead of day indices (today): Without prev_day, you lose both the distance today - prev_day and the target slot in answer.
  • Using if instead of while when popping: A single warm spike (such as 70 in Example 1) can resolve several earlier days at once; an if pops only the most recent one and breaks stack order.
  • Thinking nested loops force O(n^2) time: Because each index is pushed once and popped at most once, the while body executes at most n times in total across the entire call.

Alternative approaches

  • Right-to-left monotonic stack: Sweep backward from n - 1 down to 0, popping any future index cand with temps[cand] <= temps[i]; the surviving top (if any) is the nearest hotter day. Since temperatures on that stack strictly increase downward and lie in [30, 100], it holds at most 71 indices!
  • Right-to-left skip-jumping in answer (O(1) extra space): Sweep backward and jump directly from j to j + answer[j] whenever temps[j] <= temps[i], eliminating the stack altogether (see the second follow-up).

Follow-up questions

  • What changes if we instead want the number of days until the next strictly colder reading? Flip the comparison in the while condition from < to > (while waiting_days and temps[waiting_days[-1]] > today_temp:). Then waiting_days keeps readings in monotonic non-decreasing order from bottom to top (warmest unresolved day on top), preserving O(n) time and O(n) space.
  • How much auxiliary memory does the stack approach require, and how can you reduce extra space to O(1) on massive inputs? Beyond the O(n) output list answer, the left-to-right stack uses up to O(n) auxiliary memory. You can drop extra memory to O(1) while maintaining O(n) time by scanning right to left and treating answer as a skip table: when testing j = i + 1 for day i, if temps[j] <= temps[i] and answer[j] > 0, no day in (j, j + answer[j]) beats temps[j] (or temps[i]), so jump straight to j += answer[j]. Every skipped day becomes permanently enclosed inside [i, i + answer[i]), so no earlier day ever visits it again — bounding total jumps across all days by O(n): python answer = [0] * len(temps) for i in range(len(temps) - 2, -1, -1): j = i + 1 while temps[j] <= temps[i] and answer[j] > 0: j += answer[j] if temps[j] > temps[i]: answer[i] = j - i
  • Suppose readings arrive one per day over a live stream instead of an in-memory list. How would you emit wait counts online while bounding memory? The left-to-right monotonic stack already works online! Keep (day_index, temp) pairs on the stack; as (today, today_temp) arrives, pop every pair with temp < today_temp, immediately emit (prev_day, today - prev_day) downstream, and push (today, today_temp) (events naturally emit out of arrival order because day i's wait is unknown until its hotter day arrives). To cap memory during arbitrarily long cooling streaks, enforce a maximum horizon of K days with a deque (a double-ended queue with O(1) push/pop at both ends): evict any front entry once today - oldest_day > K and emit (oldest_day, 0), bounding memory at O(K).

Follow-up questions

Similar questions

More eBay interview questions

All 41 eBay questions →