Talentd
FleetCode
Make and follow sheets.Sign in

Daily Temperatures solution and explanation

MediumArrayMonotonic StackStack6 min read69.1% acceptanceUpdated 9 Apr 2026
Daily Temperatures - Monotonic Stack - Leetcode 739 - PythonNeetCode · 11:52 · 372K viewsWatch on YouTube
9 more videos on this problem
  1. Daily Temperatures - Monotonic Stack - Leetcode 739 - PythonNeetCode · 11:52 · 372K views
  2. Daily Temperatures (LeetCode 739) | Full solution with animations and examples | Study AlgorithmsNikhil Lohia · 12:51 · 41K views
  3. Daily Temperatures - Leetcode 739 - Stacks (Python)Greg Hogg · 12:35 · 28K views
  4. Leetcode Visualized: 739. Daily TemperaturesAlexander Le · 18:18 · 23K views
  5. Daily Temperatures | Time Complexity Explained | Google | Leetcode 739codestorywithMIK · 21:51 · 20K views
  6. 739. Daily Temperatures | Monotonic Stack | Space Optimisation O(1)Aryan Mittal · 28:11 · 5K views
  7. LeetCode 739: Daily TemperaturesEngineering Digest · 15:01 · 4K views
  8. Daily Temperatures | Leetcode 739 | Live coding session 🔥🔥🔥🔥 | Monotonic StackCoding Decoded · 13:42 · 3K views
  9. 739. Daily Temperatures #Leetcode | Explanation and CodeReturn Zero · 7:01 · 1K views
  10. Daily Temperatures - LeetCode 739 - Python - Visually ExplainedHello Byte · 6:00 · 766 views

The problem

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

Example 1:

Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]

Example 2:

Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]

Example 3:

Input: temperatures = [30,60,90]
Output: [1,1,0]

Constraints:

  • 1 <= temperatures.length <= 105
  • 30 <= temperatures[i] <= 100

Approach overview

Problem Overview: You receive an array where temperatures[i] represents the temperature on day i. For every day, compute how many days you must wait until a warmer temperature appears. If no warmer day exists, return 0 for that position.

Approach 1: Monotonic Stack (O(n) time, O(n) space)

The optimal solution uses a monotonic decreasing stack that stores indices of days whose warmer temperature hasn't been found yet. As you iterate through the array, compare the current temperature with the temperature at the index on top of the stack. If the current temperature is higher, you've found the next warmer day for that index. Pop the index and compute the distance currentIndex - previousIndex. Continue until the stack is empty or the top temperature is greater than or equal to the current one. Push the current index afterward.

This works because each index is pushed and popped at most once, keeping the algorithm linear. The stack maintains a decreasing sequence of temperatures, which guarantees that when a warmer day appears it resolves multiple previous days efficiently. This is a classic use of stack combined with the monotonic stack pattern commonly used in "next greater element" style problems.

Approach 2: Optimized Array Traversal (O(n) time, O(n) space)

Another strategy scans the array from right to left while using previously computed answers to skip unnecessary checks. Maintain a result array initialized with zeros. For each index i, jump forward using i + result[i] until you find a warmer temperature or reach the end. If temperatures[j] is warmer, store j - i. If not, keep jumping using previously stored answers.

This method avoids an explicit stack but still leverages the idea that future results are already computed. In practice, it behaves similarly to dynamic programming over an array. Each index is visited a limited number of times, keeping overall complexity linear. The approach is useful in languages where array operations are simple and predictable.

Recommended for interviews: The monotonic stack solution is the expected answer. Interviewers often use this problem to test whether you recognize the "next greater element" pattern and can apply a monotonic structure efficiently. Brute force reasoning (checking future days) demonstrates baseline understanding, but implementing the O(n) stack solution shows strong algorithmic pattern recognition.

Approach 1: Monotonic Stack Approach

The monotonic stack approach is an efficient way to solve this problem by maintaining a stack to keep track of temperatures and their indices. We iterate over the temperatures, and for each temperature, we check if it is warmer than the temperature represented by the top index of the stack. If it is, we calculate the difference in indices to determine the number of days to wait for a warmer temperature.

This approach uses a stack to store indices of temperatures that are waiting for a warmer day. As we iterate through the list, for each temperature, we pop from the stack until the current temperature is not warmer than the temperature at the index stored at the top of the stack.

def dailyTemperatures(temperatures):
    answer = [0] * len(temperatures)
    stack = []  # stores indices
    for i, temp in enumerate(temperatures):
        while stack and temperatures[stack[-1]] < temp:
            prev_index = stack.pop()
            answer[prev_index] = i - prev_index
        stack.append(i)
    return answer
#include <vector>
#include <stack>
using namespace std;

vector<int> dailyTemperatures(vector<int>& temperatures) {
    vector<int> answer(temperatures.size(), 0);
    stack<int> s; // Stores indices
    for (int i = 0; i < temperatures.size(); ++i) {
        while (!s.empty() && temperatures[i] > temperatures[s.top()]) {
            int prev_index = s.top();
            s.pop();
            answer[prev_index] = i - prev_index;
        }
        s.push(i);
    }
    return answer;
}

The Python solution initializes a list 'answer' filled with zeros. A stack is maintained to store indices of temperatures waiting for a higher temperature. As we iterate through the 'temperatures' list, we compare the current temperature with temperatures indicated by indices in the stack. If the current temperature is higher, that means we have found a higher temperature for the indices in the stack. We then update the 'answer' list with the number of days. Otherwise, the current index is added to the stack.

Complexity

Time Complexity: O(n) - Each index is pushed and popped from the stack once.
Space Complexity: O(n) - Space used by the stack to store indices.

Try this approach in the editor

Approach 2: Optimized Array Traversal

This approach traverses the temperature list backwards, efficiently discovering the number of days until encountering a warmer temperature. The main idea is to use an array to store the index of the next day for each temperature that is higher. By starting from the end and moving backwards, the solution is optimized in terms of lookups and updates.

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] answer = new int[n];
        int[] next = new int[101];
        Arrays.fill(next, Integer.MAX_VALUE);
        for (int i = n - 1; i >= 0; i--) {
            int warmerIndex = Integer.MAX_VALUE;
            for (int t = temperatures[i] + 1; t <= 100; t++) {
                warmerIndex = Math.min(warmerIndex, next[t]);
            }
            if (warmerIndex < Integer.MAX_VALUE) {
                answer[i] = warmerIndex - i;
            }
            next[temperatures[i]] = i;
        }
        return answer;
    }
}
function dailyTemperatures(temperatures) {
    const n = temperatures.length;
    const answer = Array(n).fill(0);
    const next = Array(101).fill(Infinity);
    for (let i = n - 1; i >= 0; i--) {
        let minIndex = Infinity;
        for (let t = temperatures[i] + 1; t <= 100; t++) {
            if (next[t] < minIndex) {
                minIndex = next[t];
            }
        }
        if (minIndex < Infinity) {
            answer[i] = minIndex - i;
        }
        next[temperatures[i]] = i;
    }
    return answer;
}

In this Java solution, we use an auxiliary array 'next' to store the closest index for each possible temperature. By iterating through the temperatures from the end to the beginning, we update the 'next' array and compute the number of days to a warmer temperature for each day.

Complexity

Time Complexity: O(n * W) - Where W is the range of temperature values (bounded by a constant, thus linear in practice).
Space Complexity: O(W) - Space used by the array to store the closest warmer day's index.

Try this approach in the editor

Approach 3: Monotonic Stack

This problem requires us to find the position of the first element greater than each element to its right, which is a typical application scenario for a monotonic stack.

We traverse the array temperatures from right to left, maintaining a stack stk that is monotonically increasing from top to bottom in terms of temperature. The stack stores the indices of the array elements. For each element temperatures[i], we continuously compare it with the top element of the stack. If the temperature corresponding to the top element of the stack is less than or equal to temperatures[i], we pop the top element of the stack in a loop until the stack is empty or the temperature corresponding to the top element of the stack is greater than temperatures[i]. At this point, the top element of the stack is the first element greater than temperatures[i] to its right, and the distance is stk.top() - i. We update the answer array accordingly. Then we push temperatures[i] onto the stack and continue traversing.

After the traversal, we return the answer array.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array temperatures.

function dailyTemperatures(temperatures: number[]): number[] {
    const n = temperatures.length;
    const ans: number[] = Array(n).fill(0);
    const stk: number[] = [];
    for (let i = n - 1; ~i; --i) {
        while (stk.length && temperatures[stk.at(-1)!] <= temperatures[i]) {
            stk.pop();
        }
        if (stk.length) {
            ans[i] = stk.at(-1)! - i;
        }
        stk.push(i);
    }
    return ans;
}
func dailyTemperatures(temperatures []int) []int {
	n := len(temperatures)
	ans := make([]int, n)
	stk := []int{}
	for i := n - 1; i >= 0; i-- {
		for len(stk) > 0 && temperatures[stk[len(stk)-1]] <= temperatures[i] {
			stk = stk[:len(stk)-1]
		}
		if len(stk) > 0 {
			ans[i] = stk[len(stk)-1] - i
		}
		stk = append(stk, i)
	}
	return ans
}
impl Solution {
    pub fn daily_temperatures(temperatures: Vec<i32>) -> Vec<i32> {
        let n = temperatures.len();
        let mut stk: Vec<usize> = Vec::new();
        let mut ans = vec![0; n];

        for i in (0..n).rev() {
            while let Some(&top) = stk.last() {
                if temperatures[top] <= temperatures[i] {
                    stk.pop();
                } else {
                    break;
                }
            }
            if let Some(&top) = stk.last() {
                ans[i] = (top - i) as i32;
            }
            stk.push(i);
        }

        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Monotonic Stack Approach

Time Complexity: O(n) - Each index is pushed and popped from the stack once.
Space Complexity: O(n) - Space used by the stack to store indices.

Optimized Array Traversal

Time Complexity: O(n * W) - Where W is the range of temperature values (bounded by a constant, thus linear in practice).
Space Complexity: O(W) - Space used by the array to store the closest warmer day's index.

Monotonic Stack–

Complexity analysis

ApproachTimeSpaceWhen to Use
Monotonic StackO(n)O(n)Best general solution. Ideal for next greater element style problems.
Optimized Array TraversalO(n)O(n)When scanning from right to left and reusing computed results is easier than maintaining a stack.

Frequently asked questions

Is Daily Temperatures easy or hard?

Daily Temperatures is rated Medium difficulty on LeetCode. The challenge is recognizing the monotonic stack pattern rather than implementing complex logic. Once you identify it as a next greater element problem, the implementation becomes straightforward.

Daily Temperatures Python/Java solution

Python implementations typically use a list as a stack, pushing indices and popping when a warmer temperature is found. Java solutions often use Stack or Deque structures. Both implementations achieve O(n) time complexity using the monotonic stack technique.

How to solve Daily Temperatures in O(n)?

Use a monotonic decreasing stack that stores indices of unresolved temperatures. While iterating through the array, compare the current temperature with the stack's top index. If the current value is higher, pop the index and record the day difference. Continue until the stack is valid again and push the current index.

What is the best approach for Daily Temperatures?

The monotonic stack approach is the most efficient and commonly expected solution. It processes the array once while maintaining indices of decreasing temperatures. Each element is pushed and popped at most once, resulting in O(n) time and O(n) space complexity.

Is Daily Temperatures asked at Google/Amazon/Meta?

Daily Temperatures appears frequently in interview preparation sets and has been reported in interviews at companies like Amazon and Meta. The problem tests understanding of monotonic stacks and next greater element patterns, which are common interview topics.

What data structure is used in Daily Temperatures?

The key data structure is a stack, specifically a monotonic decreasing stack that stores indices of temperatures. This structure ensures that unresolved days remain ordered so a warmer day can resolve multiple previous entries efficiently.

What is the time complexity of Daily Temperatures?

The optimal solution runs in O(n) time because each temperature index is processed at most twice—once when pushed to the stack and once when popped. Space complexity is O(n) due to the stack or result array used to track unresolved days.

Comments

Now write it yourselfClose this page and solve Daily Temperatures in the editor, without looking.
Practise Daily Temperatures