This problem follows the Monotonic Stack pattern, commonly found in the Stack category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Maintain a decreasing stack of indices. Pop when current temp is higher.
A monotonic decreasing stack ensures each index is pushed and popped exactly once — when you pop, you've found the next warmer day.
result = [0] * len(temperatures)
stack = [] # stores indices
for i, temp in enumerate(temperatures):
while stack and temperatures[stack[-1]] < temp:
j = stack.pop()
result[j] = i - j
stack.push(i)
return resultPractice Daily Temperatures and similar Stack problems with flashcards. Build pattern recognition through active recall.
Practice this problem