AlgoInsight

DSA problem

Daily Temperatures

MediumMonotonic StackPattern: Monotonic Stacktop150FreeAmazonGoogleMicrosoftBloombergAppleMeta

Given an integer array temperatures representing the daily temperatures, return an array answer where answer[i] is the number of days you have to wait after day i to get a warmer temperature. If no future day has a warmer temperature, set answer[i] to 0.

The brute force is the obvious double loop: for each day, scan to its right until you find a warmer temperature, costing O(n²) time. That works for tiny inputs but is too slow for n up to 10⁵.

The optimal approach uses a monotonic decreasing stack of indices. As we iterate left-to-right, the stack stores indices whose answer we have not yet computed; the corresponding temperatures decrease from bottom to top. When we see a day i whose temperature exceeds the temperature at the stack's top, we have just discovered the next warmer day for that pending index — pop it and set answer[top] = i - top. We keep popping while the current temperature still beats the new top.

This is the canonical "next greater element on indices" pattern. Each index is pushed exactly once and popped at most once, so the total work is linear despite the inner while loop. Indices that remain on the stack at the end of the iteration have no warmer future day, and their answer stays at the default 0.

Examples

Example 1
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Explanation: Day 0 (73): next warmer is day 1 (74) → wait 1. Day 2 (75): next warmer is day 6 (76) → wait 4. Days 6 and 7 have no future warmer day → 0.
Example 2
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Explanation: Each day except the last finds a warmer day on the very next index.
Example 3
Input: temperatures = [30,60,90]
Output: [1,1,0]
Explanation: Days 0 and 1 each find a warmer day the next day; the last day has no warmer day to come.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

monotonic-stackstackarray

Browse all DSA problems