21. Daily Temperatures
mediumAsked at Byju'sFor each day in an array, return how many days until a warmer temperature occurs.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of integers temperatures representing the 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 there is no future day for which this is possible, keep answer[i] equal to zero.
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 next-warm scan
For each day, scan forward until a warmer day is found.
- Time
- O(n^2)
- Space
- O(n)
const res=new Array(t.length).fill(0);
for(let i=0;i<t.length;i++)
for(let j=i+1;j<t.length;j++)
if(t[j]>t[i]){res[i]=j-i;break;}
return res;Tradeoff:
2. Monotonic decreasing stack
Push indices onto a stack while temperatures stay non-increasing. When a warmer day arrives, pop pending indices and record the gap.
- Time
- O(n)
- Space
- O(n)
function dailyTemperatures(temperatures) {
const res = new Array(temperatures.length).fill(0);
const stack = [];
for (let i = 0; i < temperatures.length; i++) {
while (stack.length && temperatures[i] > temperatures[stack[stack.length - 1]]) {
const j = stack.pop();
res[j] = i - j;
}
stack.push(i);
}
return res;
}Tradeoff:
Byju's-specific tips
Byju's video-tutoring analytics looks for 'next-better engagement event' in streaming watch logs, so reach for the monotonic-stack analogy to win bonus signal.
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 Byju's interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →