Daily Temperatures
🎯 Difficulty: MEDIUM
🔗 LeetCodeProblem Statement
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example:
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Approach: Monotonic Stack
To efficiently find the next greater element (in this case, the next warmer day), we can use a Monotonic Decreasing Stack. Instead of storing the temperatures themselves, the stack will store the indices of the days. This allows us to easily calculate the distance (number of days) between two temperatures.
- Initialize an array
resof the same length astemperatures, filled with0. This handles cases where no warmer day is found. - Initialize an empty
stackto keep track of the indices of the days we haven’t found a warmer temperature for yet. - Iterate through each day
iand itstemperaturein the array:- While the
stackis not empty AND the currenttemperatureis strictly greater than the temperature at the index on the top of the stack:- We have found a warmer day for the day at the top of the stack!
- Pop the index from the stack (let’s call it
prevIndex). - Calculate the number of days waited:
i - prevIndex. - Set
res[prevIndex] = i - prevIndex.
- Push the current day’s index
ionto the stack so we can find its next warmer day later.
- While the
- After the loop, return the
resarray.
Solution
/**
* @param {number[]} temperatures
* @return {number[]}
*/
function dailyTemperatures(temperatures) {
const res = new Array(temperatures.length).fill(0);
const stack = []; // Stores indices
for (let i = 0; i < temperatures.length; i++) {
const t = temperatures[i];
// While current temp is warmer than the temp at the index on top of the stack
while (stack.length > 0 && t > temperatures[stack[stack.length - 1]]) {
const prevIndex = stack.pop();
res[prevIndex] = i - prevIndex;
}
stack.push(i);
}
return res;
}
Complexity Analysis
- Time Complexity: , where is the length of the
temperaturesarray. Although there is a nestedwhileloop, every index is pushed onto the stack exactly once and popped from the stack at most once. Thus, the inner loop runs at most times globally. - Space Complexity: in the worst case (e.g., temperatures are strictly decreasing like
[100, 90, 80, 70]), where the stack will store all indices.