easyStackStack

Daily Temperatures

easyTime: O(n)Space: O(n)

Recognize the pattern

find next warmer daynext greater elementlook forward in array

Brute force idea

If you approach Daily Temperatures in the most literal way possible, you get this: For each day, scan forward to find the next warmer temperature. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

The real unlock in Daily Temperatures comes when you notice this: Use a monotonic decreasing stack of indices; pop when current temp is warmer. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Daily Temperatures is this: The stack holds indices of days still waiting for a warmer day, in decreasing temperature order. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

One easy way to drift off course in Daily Temperatures is this: Storing temperatures instead of indices — you need indices to calculate the day difference. The fix is usually to return to the meaning of each move, not just the steps themselves.

Stack Pattern