Daily Temperatures DSA Solution - Monotonic Stack - Study Chapter | QuizMaker

Daily Temperatures explained with brute force, optimized monotonic stack approach, dry run, edge cases, complexity, and Python, C++, Java code.

Read
12m
Type
Chapter
Access
Free

Course

DSA Course: Interview Patterns and Problem Solving

Topic

Module 4: Stack & Queue

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
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> answer(temperatures.size(), 0);
        stack<int> st;

        for (int i = 0; i < temperatures.size(); i++) {
            while (!st.empty() && temperatures[i] > temperatures[st.top()]) {
                int prev = st.top();
                st.pop();
                answer[prev] = i - prev;
            }
            st.push(i);
        }

        return answer;
    }
};
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int[] answer = new int[temperatures.length];
        Deque<Integer> stack = new ArrayDeque<>();

        for (int i = 0; i < temperatures.length; i++) {
            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                int prev = stack.pop();
                answer[prev] = i - prev;
            }
            stack.push(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

Interview Checklist

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.

Tags

Open on QuizMaker