21. Daily Temperatures
mediumAsked at Riot GamesFor each day, find how many days until a warmer temperature — Riot uses the monotonic stack pattern when reasoning about next-event-time queries on server tick logs.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of integers temperatures representing daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If none, answer[i] = 0.
Constraints
1 <= temperatures.length <= 10^530 <= temperatures[i] <= 100
Examples
Example 1
temperatures=[73,74,75,71,69,72,76,73][1,1,4,2,1,1,0,0]Example 2
temperatures=[30,40,50,60][1,1,1,0]Approaches
1. Nested forward scan
For each index scan forward until a warmer day is found.
- Time
- O(n^2)
- Space
- O(1)
const ans = new Array(temperatures.length).fill(0);
for (let i=0;i<temperatures.length;i++) {
for (let j=i+1;j<temperatures.length;j++) {
if (temperatures[j]>temperatures[i]) { ans[i]=j-i; break; }
}
}
return ans;Tradeoff:
2. Monotonic decreasing stack
Push indices on a stack; pop when current temperature exceeds the top, recording the distance. Same monotonic stack Riot uses to compute next-event-time deltas across server tick streams in O(n).
- Time
- O(n)
- Space
- O(n)
function dailyTemperatures(t) {
const ans = new Array(t.length).fill(0);
const stack = [];
for (let i=0;i<t.length;i++) {
while (stack.length && t[i] > t[stack[stack.length-1]]) {
const j = stack.pop();
ans[j] = i - j;
}
stack.push(i);
}
return ans;
}Tradeoff:
Riot Games-specific tips
Riot expects you to articulate why each index is pushed and popped exactly once — the same amortized analysis that justifies their monotonic event-queue traversals at server tick rate.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Daily Temperatures and other Riot Games interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →