DSA Stacks

Daily Temperatures

Monotonic decreasing stack — pop indices whose temperature is exceeded and record the gap.

Medium
Time O(n) Space O(n)
LeetCode
3 min read
monotonic-stack array

Problem#

For each day, return the number of days until a warmer temperature. Return 0 if no future day is warmer.

Examples#

  • [73,74,75,71,69,72,76,73][1,1,4,2,1,1,0,0]
  • [30,40,50,60][1,1,1,0]
  • [30,60,90][1,1,0]

Constraints#

  • 1 <= temperatures.length <= 10^5, 30 <= temperatures[i] <= 100.

Approach#

Maintain a stack of indices with temperatures in non-increasing order. For each new day i, while the top of the stack has a smaller temperature, pop and set its answer to i - top. Push i.

Solution#

Daily Temperatures
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& t) {
int n = t.size();
vector<int> ans(n, 0);
stack<int> st;
for (int i = 0; i < n; ++i) {
while (!st.empty() && t[st.top()] < t[i]) {
int idx = st.top(); st.pop();
ans[idx] = i - idx;
}
st.push(i);
}
return ans;
}
};

Editorial#

Each index is pushed once and popped at most once, so the inner while loop is amortized O(1). The monotone stack invariant (decreasing temperatures) ensures every popped index’s answer is exactly the current index.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.