Daily Temperatures
Monotonic decreasing stack — pop indices whose temperature is exceeded and record the gap.
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#
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; }};func dailyTemperatures(t []int) []int { n := len(t) ans := make([]int, n) st := []int{} for i := 0; i < n; i++ { for len(st) > 0 && t[st[len(st)-1]] < t[i] { idx := st[len(st)-1] st = st[:len(st)-1] ans[idx] = i - idx } st = append(st, i) } return ans}from typing import List
class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: n = len(temperatures) ans = [0] * n st: List[int] = [] for i in range(n): while st and temperatures[st[-1]] < temperatures[i]: idx = st.pop() ans[idx] = i - idx st.append(i) return ansfunction dailyTemperatures(temperatures) { const n = temperatures.length; const ans = new Array(n).fill(0); const st = []; for (let i = 0; i < n; i++) { while (st.length && temperatures[st[st.length - 1]] < temperatures[i]) { const idx = st.pop(); ans[idx] = i - idx; } st.push(i); } return ans;}class Solution { public int[] dailyTemperatures(int[] temperatures) { int n = temperatures.length; int[] ans = new int[n]; Deque<Integer> st = new ArrayDeque<>(); for (int i = 0; i < n; i++) { while (!st.isEmpty() && temperatures[st.peek()] < temperatures[i]) { int idx = st.pop(); ans[idx] = i - idx; } st.push(i); } return ans; }}function dailyTemperatures(temperatures: number[]): number[] { const n = temperatures.length; const ans: number[] = new Array(n).fill(0); const st: number[] = []; for (let i = 0; i < n; i++) { while (st.length && temperatures[st[st.length - 1]] < temperatures[i]) { const idx = st.pop() as number; 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#
Related#