Python coding

Days until a warmer day

You get temps, the daily temperatures in order. For each day, return how many days you must wait until a strictly warmer day. If no warmer day comes, that day's answer is 0.

Aim for O(n): comparing every pair of days is O(n²).

Besides the tests, one large input (7,000 days) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • days_until_warmer([73,74,75,71,69,72,76,73]) → [1,1,4,2,1,1,0,0]
  • days_until_warmer([30,40,50,60]) → [1,1,1,0]
  • days_until_warmer([60,50,40,30]) → [0,0,0,0]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Days still waiting for a warmer one form a stack: the most recent waiting day is the first one a warm day can answer.

Hint 2

Push indexes, not temperatures. While day i is warmer than the top, pop it as j and record i - j.

Solution and why it works
pythonO(n) · O(n)
def days_until_warmer(temps: list[int]) -> list[int]:
    ans, stack = [0] * len(temps), []
    for i, t in enumerate(temps):
        while stack and temps[stack[-1]] < t:
            j = stack.pop()
            ans[j] = i - j
        stack.append(i)
    return ans

The stack keeps indexes of days still waiting, with temperatures that never rise from bottom to top. A warmer day pops every cooler index and answers it with the distance i - j. Each index is pushed and popped at most once, so the pass is O(n) despite the inner loop. Use a strict <: an equal temperature is not warmer, so that day keeps waiting.