Daily Temperatures — LeetCode 739 Python Solution

MediumStackArrayMonotonic Stack
Problem
#739
Pattern
Stack
Reading time
2 min

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

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

Python solution

Python
class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        stk = []
        n = len(temperatures)
        ans = [0] * n
        for i in range(n - 1, -1, -1):
            while stk and temperatures[stk[-1]] <= temperatures[i]:
                stk.pop()
            if stk:
                ans[i] = stk[-1] - i
            stk.append(i)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 739. Daily Temperatures is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150 and LeetCode 75.

Frequently asked questions

How hard is LeetCode 739. Daily Temperatures?
LeetCode 739. Daily Temperatures is rated Medium on LeetCode.
What is the time complexity of LeetCode 739. Daily Temperatures?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 739. Daily Temperatures?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 739. Daily Temperatures cover?
LeetCode 739. Daily Temperatures is tagged Stack, Array and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview