Article start
DSA Course: Interview Patterns and Problem Solving
Module 4: Stack & Queue

Daily Temperatures: Monotonic stack Pattern

Use a decreasing stack of unresolved days to find the next warmer temperature.

May 28, 2026·35

Learning Outcome

After this lesson, you should be able to use a monotonic stack to resolve "next greater" style questions in one pass.

Problem Statement

Given daily temperatures, return an array where each value tells how many days you must wait for a warmer temperature. If there is no future warmer day, use 0.

InputOutputWhy
[73,74,75,71,69,72,76,73][1,1,4,2,1,1,0,0]For day 2 at 75, the next warmer day is 4 days later at 76.

Brute Force Approach

For each day, scan all later days until a warmer temperature is found.

This is clear, but in the worst case it costs O(n^2).

Optimized Approach

Keep a stack of indices whose warmer day has not been found yet. The stack is decreasing by temperature. When the current temperature is warmer than the temperature at the stack top, pop that index and fill its answer.

Exact Pseudocode

answer = array of zeroes
stack = empty stack of indices
for i from 0 to length(temperatures) - 1:
  while stack is not empty and temperatures[i] > temperatures[stack.top]:
    prev = pop stack
    answer[prev] = i - prev
  push i
return answer

Reference Code

class Solution:
    def dailyTemperatures(self, temperatures):
        answer = [0] * len(temperatures)
        stack = []

        for i, temp in enumerate(temperatures):
            while stack and temp > temperatures[stack[-1]]:
                prev = stack.pop()
                answer[prev] = i - prev
            stack.append(i)

        return answer

Sample Dry Run

daytempstack beforeAction
073[]Push 0
174[0]74 warms day 0, answer[0] = 1, push 1
275[1]75 warms day 1, answer[1] = 1, push 2
371[2]Not warmer than 75, push 3
572[2,3,4]Resolve days 4 and 3

Complexity

MeasureValueReason
TimeO(n)Each index is pushed once and popped once.
SpaceO(n)The stack may hold many unresolved days.

Edge Cases

  • Strictly decreasing temperatures produce all zeroes.
  • Equal temperatures are not warmer.
  • Single-day input returns [0].

Interview Checklist

  • Store indices, not temperatures, so you can compute distance.
  • Use >, not >=, because equal is not warmer.
  • Leave unresolved days as zero.

FAQs

Why is this a monotonic stack?

The stack keeps unresolved days in decreasing temperature order.

Why store indices?

The answer requires the number of days waited, which is the current index minus the previous index.

What is the core pattern?

Next greater element with a monotonic stack.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.