Algo-Sim › Stacks & Monotonic Stack

Daily Temperatures

Medium · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input

For each day, how many days until a warmer temperature? Use 0 if no warmer day comes.

Problem

Given daily temperatures, return an array where entry i is how many days you must wait after day i for a strictly warmer day, or 0 if no warmer day comes.

Constraints

Edge cases to test

Follow-up questions

Is there an O(1)-extra-space version?
Walk from the right and jump with the answers already found: j += answer[j] until warmer. O(n) amortized.
Why decreasing on the stack?
Each day waits until a warmer one pops it; days still waiting are always colder than the ones below them.

Solution

Java

public int[] dailyTemperatures(int[] temps) {
    int n = temps.length;
    int[] result = new int[n];
    Deque<Integer> stack = new ArrayDeque<>();
    for (int i = 0; i < n; i++) {
        while (!stack.isEmpty() && temps[stack.peek()] < temps[i]) {
            int idx = stack.pop();
            result[idx] = i - idx;
        }
        stack.push(i);
    }
    return result;
}

Python

def daily_temperatures(temps):
    n = len(temps)
    result = [0] * n
    stack = []
    for i in range(n):
        while stack and temps[stack[-1]] < temps[i]:
            idx = stack.pop()
            result[idx] = i - idx
        stack.append(i)
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> dailyTemperatures(vector<int> &temps) {
        int n = int(temps.size());
        vector<int> result = vector<int>(n);
        deque<int> stack = {};
        for (int i = 0; i < n; i++) {
            while (!stack.empty() && temps[stack.back()] < temps[i]) {
                int idx = stack.back();
                stack.pop_back();
                result[idx] = i - idx;
            }
            stack.push_back(i);
        }
        return result;
    }
};

More Stacks & Monotonic Stack problems