19. Daily Temperatures
mediumAsked at FlipkartFor each day report how many days until a warmer temperature — Flipkart uses it to test monotonic-stack fluency before harder pricing-window problems.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of integer temperatures representing daily temperatures, return an array answer where answer[i] is the number of days you have to wait after day i to get a warmer temperature. Use 0 when there is no future day with a warmer value.
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. Brute force scan
For each day, scan forward until you find a warmer value.
- Time
- O(n^2)
- Space
- O(1)
for (let i=0;i<n;i++) { for (let j=i+1;j<n;j++) if (t[j]>t[i]) { out[i]=j-i; break; } }Tradeoff:
2. Monotonic decreasing stack
Keep a stack of indices waiting for a warmer day. When the current value exceeds the stack top, pop and record the distance. Each index pushed/popped once.
- Time
- O(n)
- Space
- O(n)
function dailyTemperatures(t) {
const out = 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();
out[j] = i - j;
}
stack.push(i);
}
return out;
}Tradeoff:
Flipkart-specific tips
Flipkart screeners watch for whether you store indices or values on the stack — storing indices is the give-away that you have done this kind of problem before.
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 Flipkart interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →