StackMedium

Daily Temperatures Visualizer

What is Daily Temperatures

For each day, return how many days you must wait until a warmer temperature. If no warmer day exists, the answer is 0.

Approach

Keep a decreasing stack of indexes. A warmer day pops every cooler day still waiting and writes i - j.

Visualization & algorithm

Waiting days, then the wait counts
ans = [0]*n
stack holds indexes
while top is cooler than today:
ans[pop] = i - popped index
push i
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.

Complexity

PieceCostWhy
TimeO(n)Each day is pushed and popped once.
SpaceO(n)A falling forecast fills the stack.

Implementation

def solve(self, temps):
    n = len(temps)
    ans = [0]*n
    st = []
    for i, t in enumerate(temps):
        while st and temps[st[-1]] < t:
            j = st.pop()
            ans[j] = i - j
        st.append(i)
    return ans