739. Daily Temperatures
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Stack
- Time
- —
- Space
- —
Standard Solution (C++)
SummaryGiven a list of daily temperatures, find for each day how many days you must wait until a warmer temperature arrives, returning 0 if no such day exists.
Approach
- Use a monotonic decreasing stack that stores indices of days whose "next warmer day" has not yet been found.
- For each new temperature, pop all stack entries whose temperature is strictly less than the current one — the wait for those days is
current_index - popped_index. - Push the current index onto the stack; anything left over at the end keeps its default answer of 0.
- Every index is pushed and popped at most once, giving linear time overall.
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> result(n, 0);
// Stack holds indices of days awaiting a warmer future day.
// Invariant: temperatures at stacked indices are in non-increasing order.
stack<int> mono;
for (int i = 0; i < n; ++i) {
// Current day is warmer than days on the stack — resolve their wait.
while (!mono.empty() && temperatures[mono.top()] < temperatures[i]) {
result[mono.top()] = i - mono.top();
mono.pop();
}
mono.push(i);
}
// Remaining indices never found a warmer day; result stays 0.
return result;
}
};
Time O(n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
using namespace std;
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n=temperatures.size();
vector<int> res(n, 0);
vector<int> st;
st.reserve(n);
for(int i=0; i<n; ++i){
int cur=temperatures[i];
while(!st.empty() && temperatures[st.back()]<cur){
res[st.back()]=i-st.back();
st.pop_back();
}
st.push_back(i);
}
return res;
}
};
// Time: O(N), where N is the length of the input array, since each index is pushed and popped at most once.
// Space: O(N), in the worst case when the input array is strictly decreasing, the stack will hold all indices, and the output array also takes O(N) space. My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.