Daily Temperatures — Monotonic Decreasing Stack

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

Problem 261 · Daily Temperatures

Difficulty: Medium · Pattern: Monotonic Decreasing Stack

For each day, find the number of days until a warmer temperature.

Solutions

// C
int* dailyTemperatures(int* temps, int n, int* returnSize) {
    int* res = calloc(n, sizeof(int)); int stack[n]; int top = 0;
    *returnSize = n;
    for (int i = 0; i < n; i++) {
        while (top > 0 && temps[stack[top-1]] < temps[i]) {
            int j = stack[--top]; res[j] = i - j;
        }
        stack[top++] = i;
    }
    return res;
}
// C++
vector<int> dailyTemperatures(vector<int>& T) {
    int n = T.size(); vector<int> res(n, 0); stack<int> st;
    for (int i = 0; i < n; i++) {
        while (!st.empty() && T[st.top()] < T[i]) {
            res[st.top()] = i - st.top(); st.pop();
        }
        st.push(i);
    }
    return res;
}
// Java
public int[] dailyTemperatures(int[] T) {
    int n = T.length; int[] res = new int[n]; Deque<Integer> stack = new ArrayDeque<>();
    for (int i = 0; i < n; i++) {
        while (!stack.isEmpty() && T[stack.peek()] < T[i])
            res[stack.peek()] = i - stack.pop();
        stack.push(i);
    }
    return res;
}
# Python
def dailyTemperatures(T):
    n = len(T); res = [0]*n; stack = []
    for i, t in enumerate(T):
        while stack and T[stack[-1]] < t:
            j = stack.pop(); res[j] = i - j
        stack.append(i)
    return res

Complexity

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

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro