Look for the first later greater value or the waiting distance to it; those words suggest keeping unresolved indices until a new value is large enough to answer them.
Keep true
After each day is appended, waiting indices increase from bottom to top while their temperatures are non-increasing, and every popped index receives its first strictly warmer later day.
Reuse it
For next-greater or next-smaller problems, store unresolved indices in a monotonic stack; the first value that violates the monotonic order resolves every eligible item popped from the top.
Read it this way: Start with answer=[0,0,0,0,0,0,0,0] and an empty waiting stack. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Pattern: Decreasing stack.
Simple idea: The stack holds days still waiting for something warmer. A warmer new day
finishes every colder day at the top.
def daily_temperatures(temperatures: list[int]) -> list[int]: answer = [0] * len(temperatures) waiting: list[int] = [] for day, temperature in enumerate(temperatures): while waiting and temperatures[waiting[-1]] < temperature: earlier_day = waiting.pop() answer[earlier_day] = day - earlier_day waiting.append(day) return answer
Cost:O(n) time and O(n) space. Each index enters and leaves the stack once.