SDE & MLE Prep

739. Daily Temperatures

Problem

For each day, return how many days you must wait after it for a strictly warmer temperature, or 0 if none comes.

Example: [73,74,75,71,69,72,76,73] → [1,1,4,2,1,1,0,0]

Constraints: n ≤ 10⁵.

Decreasing stack of indices. A warmer day pops every colder index and fills its wait = i − j.

temps 73 74 75 71 69 72 76 73
i=5 (72): pops 69(idx4)->1, 71(idx3)->2     stack [75, 72]
i=6 (76): pops 72->1, 75->4                 stack [76]

Complexity: O(n).

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        res, st = [0] * len(temperatures), []
        for i, t in enumerate(temperatures):
            while st and temperatures[st[-1]] < t:
                j = st.pop()
                res[j] = i - j
            st.append(i)
        return res