Daily Temperatures solution explained

Daily Temperatures is solved with a monotonic stack: walk the days in order, keep a stack of days still waiting for a warmer one, and each time today's reading beats the day on top of the stack, pop that day and record how long it waited. Every day is pushed once and popped at most once, so the whole thing is O(n).

By Published 7 min read

The problem, reworded

You get a list of daily temperature readings in date order. Produce a list of the same length where position i holds the number of days you would wait after day i to see a temperature strictly higher than day i's. If no later day is warmer, put 0. A day with the same temperature does not count as warmer.

Readings made up for this page, with answers from the code below
ReadingsAnswerNote
[21, 19, 24, 24, 20, 26][2, 1, 3, 2, 1, 0]The two 24s both wait for the 26
[30, 28, 25][0, 0, 0]Steadily cooling, so nobody gets a warmer day
[12, 13, 14][1, 1, 0]Each day is beaten by the next one
[18, 18, 19][2, 1, 0]Equal is not warmer, so the first 18 waits two days
Readings made up for this page, with answers from the code below. Scroll sideways on a small screen.

Why it comes up

Daily Temperatures is the friendliest introduction to the monotonic stack, a pattern that otherwise feels like a trick. The interviewer wants to see you start from the obvious nested loop, notice that a cold spell makes it quadratic, and find a structure that lets each day be resolved the moment its answer appears. If you know this problem well, Largest Rectangle in Histogram becomes far less scary.

First pass: look ahead from each day

For every day, scan forward until you hit a warmer reading, and store the distance. It is easy to write and easy to trust. The trouble is a long run of falling temperatures followed by a hot day at the end: every day scans almost to the end, which is about n²/2 comparisons.

def wait_for_warmer_slow(temps):
    result = [0] * len(temps)
    for i in range(len(temps)):
        for j in range(i + 1, len(temps)):
            if temps[j] > temps[i]:
                result[i] = j - i
                break
    return result
Nested loops: O(n²) in the worst case.

The monotonic stack

Flip the question around. Instead of each day searching forward for its answer, let each new day settle the debts of earlier days. Keep a stack of indexes for days that have not yet seen a warmer day. When a new day arrives, compare it with the day on top. If the new day is warmer, the top day's wait is over: pop it and record the distance. Keep popping while the new day beats the top. Then push the new day, since it is now waiting too.

Why only compare with the top? Every day still on the stack lost to every day pushed after it, otherwise it would have been popped. So from bottom to top, the waiting temperatures never increase. If today cannot beat the top, which is the coolest waiting day, it cannot beat anything below it either, and the loop can stop.

def wait_for_warmer(temps):
    result = [0] * len(temps)
    pending = []  # indexes still waiting; their temps never increase upward
    for today, temp in enumerate(temps):
        while pending and temps[pending[-1]] < temp:
            earlier = pending.pop()
            result[earlier] = today - earlier
        pending.append(today)
    return result
Python: one pass with a stack of waiting indexes. O(n) time.
#include <vector>
using namespace std;

vector<int> waitForWarmer(const vector<int>& temps) {
    vector<int> result(temps.size(), 0);
    vector<int> pending;  // used as a stack of indexes
    for (int today = 0; today < (int)temps.size(); ++today) {
        while (!pending.empty() && temps[pending.back()] < temps[today]) {
            int earlier = pending.back();
            pending.pop_back();
            result[earlier] = today - earlier;
        }
        pending.push_back(today);
    }
    return result;
}
C++: the same idea with a vector used as the stack.

Trace on the first example

Days 0 (21) and 1 (19) go on the stack, since 19 does not beat 21. Day 2 (24) beats 19, so day 1 waited 1 day; it beats 21, so day 0 waited 2 days. Day 2 is pushed. Day 3 (24) does not beat 24, so it is pushed above it. Day 4 (20) is pushed too. Day 5 (26) pops day 4 (wait 1), day 3 (wait 2) and day 2 (wait 3). Nothing is left waiting except day 5, which keeps its 0.

Why it is linear

The inner while loop looks like it could make this quadratic, but count pops instead of loop iterations. Each index is pushed exactly once and can be popped at most once, so across the whole run there are at most n pops. Add the n pushes and the total work is O(n). This amortized argument is the sentence interviewers want to hear, so practice saying it.

Time and extra space
ApproachTimeExtra space
Look ahead from each dayO(n²)O(1) beyond the output
Monotonic stack, left to rightO(n)O(n) for the stack
Right to left, jumping by stored answersO(n) amortizedO(1) beyond the output
Time and extra space. Scroll sideways on a small screen.

The last row is a neat follow-up. Walk from the end. To find day i's answer, start at day i + 1 and, while that day is not warmer, jump ahead by that day's own stored wait, since nothing between it and its own warmer day can beat it either. If a stored wait is 0, there is no warmer day ahead. It avoids the stack but is harder to explain, so lead with the stack.

Edge cases

  • A single day: the answer is [0].
  • Equal neighbors: use a strict greater-than when popping, or equal days will be marked as warmer.
  • Strictly falling readings: the stack grows to n and every answer is 0, which is the stack's worst memory case.
  • Strictly rising readings: every day is popped by the next one and the stack never holds more than one item.

Frequent mistakes

  • Pushing temperatures instead of indexes, which loses the information needed to compute the distance.
  • Using greater-than-or-equal in the pop condition, which treats equal days as warmer.
  • Forgetting that unresolved days must stay 0; initializing the result to -1 and never fixing it is a classic slip.
  • Describing the solution as O(n²) because of the nested loop, or as O(n) without the push-and-pop argument.

Follow-up questions

  • Report the warmer temperature instead of the wait. Store temps[today] instead of the distance.
  • Previous warmer day instead of next. Pop while the top is not warmer than today; whatever is still on top just before you push today is the nearest earlier warmer day.
  • A circular list, where the search wraps around. Loop over the indexes twice, pushing only on the first lap.
  • A live stream of readings. The stack version works online; you emit each day's answer when it gets popped.

How to explain it

Fictional example

A short spoken version
Candidate
The nested loop is quadratic on a long cold stretch. Instead, I'll keep a stack of days still waiting for a warmer one.
Candidate
When a new day comes in, it resolves every waiting day it beats, starting from the top. The stack stays in non-increasing order, so I can stop as soon as the top is at least as warm.
Candidate
Each day is pushed once and popped at most once, so it's linear overall even with the inner loop.

Car Fleet uses the same idea of a group in front blocking those behind. Largest Rectangle in Histogram is the harder monotonic-stack problem that builds on this one, and Min Stack shows another stack that carries extra information. All of them are on the coding problems hub.

Natively as a practice partner

Practicing on a Mac or a Windows PC, you can let Natively read this prompt from a screenshot and ask it why the stack stays sorted or how to argue the linear bound. It saves a transcript and notes from your mock session, so you can review whether you explained the amortized step clearly. Details are on the AI interview assistant page.

Questions people ask

How do you solve Daily Temperatures?

Use a monotonic stack of indexes for days still waiting. For each new day, pop every waiting day it is strictly warmer than and record the distance, then push the new day. Unresolved days keep 0.

Why is the Daily Temperatures stack solution O(n) with a nested loop?

Each index is pushed once and popped at most once, so the total number of pops across the whole run is at most n. The inner loop's work is shared across all days, which makes the total linear.

What is a monotonic stack?

A stack whose values stay in sorted order from bottom to top. In Daily Temperatures the waiting temperatures never increase toward the top, so a new day only needs to compare against the top.

Can Daily Temperatures be solved without a stack?

Yes. Walk from the right and, for each day, jump forward using the waits already computed until you reach a warmer day or a day with no warmer day ahead. It is also linear, but harder to explain.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP