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): day1reaches68, which is1 - 0 = 1day later. - Day
1(68): days2,3, and4stay below68; day5hits70, giving5 - 1 = 4. - Day
2(65): day3ties at65(not strictly hotter), so both day2and day3wait until day5(70), giving3and2days respectively. - Day
4(63): day5(70) is1day away. - Days
5(70) and6(67): no later day exceeds either reading, so both entries are0.
- Day
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 receives0.
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(iftempsis empty, return[])30 <= temps[i] <= 100
Step-by-step walkthrough
Restate the goal and input rules
Given a list
tempswheretemps[i]is the temperature reading on dayi, we must return a listanswerof the same length whereanswer[i]is how many days pass (j - i) until the earliest later dayj > iwithtemps[j] > temps[i].Three rules govern every case:
- Strictly hotter (
>): a later day with the exact same reading (65after65) 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]stays0. - Scale:
tempscan contain up to10^5entries, so our solution must run inO(n)time rather thanO(n^2).
- Strictly hotter (
Start with brute force and see why it repeats work
A direct baseline stands on each day
iand scans rightward (j = i + 1, i + 2, ...) until finding a reading abovetemps[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 answerWhy does this time out on large inputs? Picture
99,999days at65degrees followed by one final day at66degrees. Day0checks99,999future days, day1checks99,998days, and so on — roughly5 * 10^9comparisons 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.
Key idea: keep unresolved days in a monotonic stack
As we sweep left to right (
today = 0, 1, ..., n - 1), we maintain a stackwaiting_daysstoring the indices of earlier days that still lack a hotter successor.When
todayarrives with readingtoday_temp:- While
waiting_daysis non-empty and the index on top (waiting_days[-1]) has a reading strictly belowtoday_temp, popprev_day = waiting_days.pop()and setanswer[prev_day] = today - prev_day. - Append
todaytowaiting_daysso it waits for a hotter day of its own.
Why is checking the top of
waiting_dayssufficient? Because temperatures alongwaiting_daysnever rise from bottom to top! Whenever a warmer reading arrives, it pops every strictly cooler day before pushing itself, keeping the coolest unresolved day atwaiting_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!- While
Write the single-pass stack loop
Two small choices keep the implementation concise:
- Push day indices rather than temperatures: an index
prev_daygives both the elapsed gaptoday - prev_dayand the stored temperaturetemps[prev_day]. - Initialize
answerto all0s: any index still sitting inwaiting_dayswhen the loop finishes never saw a hotter day, so its0default 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- Push day indices rather than temperatures: an index
Trace Example 1 and verify O(n) time
Let's trace Example 1,
temps = [64, 68, 65, 65, 63, 70, 67], writing stack entries asidx(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
whileloop nested inside aforloop stillO(n)? Count stack actions over the entire call: each of thenindices is pushed ontowaiting_daysonce and popped at most once, bounding totalwhileiterations across all days combined byn.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)(amortizedO(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 index0 .. n - 1is pushed ontowaiting_daysonce and popped at most once, so the outerforloop and innerwhileloop perform at most2nstack operations combined. - Space:
O(n). The output listanswerholdsnintegers, and in the worst case (when readings never rise, such as[88, 82, 75]or[65, 65, 65])waiting_daysholds allnindices at once.
Edge cases
- Empty input (
[]) or single day ([50]): Returns[]and[0]cleanly without extraifbranches. - All equal readings (
[65, 65, 65]): Because<is strict, no65pops an earlier65, leaving[0, 0, 0]. - Tied readings resolved together (
[65, 65, 70]): Both65s remain on the stack until70pops 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]): Day4(90) drains the entire stack in onewhileloop, returning[4, 3, 2, 1, 0]. - Boundary readings (
30and100): Nothing exceeds100, so any day at100always ends with0even if another100appears later.
Common mistakes
- Writing
<=instead of<in thewhiletest: 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): Withoutprev_day, you lose both the distancetoday - prev_dayand the target slot inanswer. - Using
ifinstead ofwhilewhen popping: A single warm spike (such as70in Example 1) can resolve several earlier days at once; anifpops 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, thewhilebody executes at mostntimes in total across the entire call.
Alternative approaches
- Right-to-left monotonic stack: Sweep backward from
n - 1down to0, popping any future indexcandwithtemps[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 most71indices! - Right-to-left skip-jumping in
answer(O(1)extra space): Sweep backward and jump directly fromjtoj + answer[j]whenevertemps[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
whilecondition from<to>(while waiting_days and temps[waiting_days[-1]] > today_temp:). Thenwaiting_dayskeeps readings in monotonic non-decreasing order from bottom to top (warmest unresolved day on top), preservingO(n)time andO(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 listanswer, the left-to-right stack uses up toO(n)auxiliary memory. You can drop extra memory toO(1)while maintainingO(n)time by scanning right to left and treatingansweras a skip table: when testingj = i + 1for dayi, iftemps[j] <= temps[i]andanswer[j] > 0, no day in(j, j + answer[j])beatstemps[j](ortemps[i]), so jump straight toj += 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 byO(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 withtemp < today_temp, immediately emit(prev_day, today - prev_day)downstream, and push(today, today_temp)(events naturally emit out of arrival order because dayi's wait is unknown until its hotter day arrives). To cap memory during arbitrarily long cooling streaks, enforce a maximum horizon ofKdays with a deque (a double-ended queue withO(1)push/pop at both ends): evict any front entry oncetoday - oldest_day > Kand emit(oldest_day, 0), bounding memory atO(K).
Follow-up questions
- What changes if we instead want the number of days until the next strictly colder reading?
- How much auxiliary memory does the stack approach require, and how can you reduce extra space to O(1) on massive inputs?
- 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?
Similar questions
- Randomized Ad Slot Allocation Under Per-User Caps
- Count Orthogonal Land Regions
- Shortest Path for a Leg-Blocked Xiangqi Horse
- Validate Numeric String Grammar
- Top K Frequent Integers
- Largest Tank Area Between Vertical Walls
More eBay interview questions
- Largest Tank Area Between Vertical Walls Medium
- Repeated Function Application and Core Data Structure Complexity Medium
- Randomized Ad Slot Allocation Under Per-User Caps Medium Pro
- Cross-Team Ownership, Manager Disagreements, and Slipping Skip-Level Deadlines Easy Pro
- Global Org Fit, Role Alignment, and On-Call Ownership Easy Pro
- Marketplace Payment Dispute Resolution Service Medium Pro
- Workplace Lunch Ordering with Daily Vendor Rotation Medium Pro
- Marketplace Product Search and Typeahead System Medium Pro
- Real-Time Top-10 Marketplace Bestseller Leaderboard Medium Pro
- Frequency-Capped Ad Placement API Medium Pro