82. Days until a warmer day
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
temps = [30, 32, 31, 35, 33][1, 2, 1, 0, 0]Example 2
temps = [40, 40, 40][0, 0, 0]Example 3
temps = [20, 10, 15, 10, 30][4, 1, 2, 1, 0]Constraints
tempshas 0 to 500 whole numbers, each from -50 to 50.
Submit also runs 8 more tests you can't see.
- Keep a stack (a list) of the indexes of days that haven't seen a warmer day yet. Start every answer at 0.
- For each new day
i, while the day on top of the stack is colder than today, pop it: its answer isi - that_day. Then pushi. - The stack always holds temperatures that don't rise from bottom to top, so each day is pushed once and popped at most once: O(n) in all. Days left on the stack at the end keep their 0.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.