100 XP

82. Days until a warmer day

Advanced stacks

Write a function days_to_warmer(temps) that takes a list of daily temperatures and returns a list of the same length: for each day, how many days you would wait until a warmer day.

  • Warmer means strictly higher: a day just as warm doesn't end the wait.
  • If no warmer day ever comes, the answer for that day is 0.
  • An empty list gives an empty list.

Looking ahead from every day takes up to n * n / 2 steps when the temperatures keep falling. A stack can do it in one pass: it holds the days still waiting, and each new day settles the waits it ends.

Example 1

Inputtemps = [30, 32, 31, 35, 33]
Output[1, 2, 1, 0, 0]
Explanation30 waits 1 day (32); 32 waits 2 (35).

Example 2

Inputtemps = [40, 40, 40]
Output[0, 0, 0]
ExplanationJust as warm is not warmer.

Example 3

Inputtemps = [20, 10, 15, 10, 30]
Output[4, 1, 2, 1, 0]
ExplanationOnly 30 is warmer than 20: 4 days later.

Constraints

  • temps has 0 to 500 whole numbers, each from -50 to 50.

Submit also runs 8 more tests you can't see.

Code
def days_to_warmer(temps):
    """Count the days until a warmer day, for each day.

    temps: list of int, one temperature per day
    Returns: list of int, the same length: days to wait
        for a higher temperature, or 0 if none comes
    """
    # Write your code here
    pass