How do you solve the daily temperatures problem with a monotonic stack?
For each day you need to know how many days pass before a strictly warmer one appears. Keep a stack of the indices whose answer is still unknown, ordered by decreasing temperature. When a new day is warmer than the day on top of the stack, that warmer day is the answer for the popped index, and the difference in indices is the number of days waited.
def daily_temperatures(temps):
result = [0] * len(temps)
stack = []
for i, temp in enumerate(temps):
while stack and temps[stack[-1]] < temp:
j = stack.pop()
result[j] = i - j
stack.append(i)
return result
print(daily_temperatures([73, 74, 75, 71, 69, 72, 76, 73]))
print(daily_temperatures([30, 40, 50, 60]))The outputs are 1, 1, 4, 2, 1, 1, 0, 0 and 1, 1, 1, 0. The 75 at index two has to wait four days for the 76 at index six, and the last two days never see a warmer one so they get zero.
The mechanism is the same decreasing stack used for the next greater element, with the answer being the difference in positions rather than the value itself. The strict comparison matters: equal temperatures do not count as warmer, so a run of equal values stays on the stack until something strictly higher arrives.
The trade-off to name is that the stack version needs random access to the temperatures by index, so it works on an array but not directly on a stream of temperatures arriving one at a time. For a stream you would either keep the stack of values and indices together, which is still linear, or accept that a later warmer day resolves several pending indices at once. The complexity is linear because every index is pushed once and popped at most once, so the amortised cost per day is constant.