For each day, count the wait until a warmer one. Keep a stack of days still waiting; a warm day pops every colder day below it.
▼The problem
LeetCode 739 (Medium). Given an array temperatures of daily temperatures, return an array answer where answer[i] is the number of days you have to wait after day i to get a warmer temperature, or 0 if no future day is warmer.
Example (LeetCode's): [73,74,75,71,69,72,76,73] → [1,1,4,2,1,1,0,0].
The solution
def daily_temperatures(temps):
ans = [0] * len(temps)
stack = [] # days still waiting
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
j = stack.pop()
ans[j] = i - j
stack.append(i)
return ansTranscript
Daily Temperatures. You get a list of daily temperatures. For each day, how long until a warmer one? If a warmer day never comes, the answer is zero.
Take this week: seventy-three, seventy-four, seventy-five, seventy-one, sixty-nine, seventy-two, seventy-six, seventy-three. Seventy-five waits four days, until seventy-six. The answer is one, one, four, two, one, one, zero, zero. The last two never see a warmer day.
The easy way: from each day, scan forward until you find something warmer. But in a long cold spell, every day colder than the one before, every scan runs all the way to the end. That's order n squared time.
Here's the trick. Keep a stack of the days still waiting. Picture each waiting day as a snowball, sized by its temperature. They stack into a snowman, smaller on top of bigger. When a warmer day arrives, it melts every colder snowball on top. Each melted day gets its answer: today minus its own day. Then today joins the stack.
Let's walk the week. Seventy-three waits. Seventy-four melts it: one day. Seventy-five melts seventy-four: one day. Seventy-one and sixty-nine stack up on top. Seventy-two melts sixty-nine, one day, then seventy-one, two days. Seventy-six melts seventy-two, one day, then seventy-five, four days. Seventy-three waits on top. The two days left on the stack never melt, so they stay zero.
In code, start every answer at zero, with an empty stack. Walk the days. While the day on top of the stack is colder than today, pop it, and set its answer to i minus j. Then push today.
Each day is pushed once and popped at most once, so it's order n time. In a cold spell nothing ever melts, and the stack holds every day: order n space.
Stack the cold days, melt them with a warm one, write down the wait. That's Daily Temperatures.