Back to DSA

Daily Temperatures

medium
Acceptance: 50%
StackMonotonic StackArray

Given an array of daily temperature readings, produce an output array where each position holds the count of days until a strictly warmer reading occurs. If no warmer day exists in the future for a given position, record 0.

Examples

Example 1:
Input:temperatures = [65,70,68,72,69,75,71,80]
Output:[1,2,1,2,1,3,1,0]
Example 2:
Input:temperatures = [55,60,65,70]
Output:[1,1,1,0]

Hints

00:00
import java.util.*;

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] result = new int[n];
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                int prev = stack.pop();
                result[prev] = i - prev;
            }
            stack.push(i);
        }
        return result;
    }
}
Time complexityO(n)
Space complexityO(n)