← All coding problems
Daily Temperatures (Monotonic Stack)
mediumStack & Queue+20 XPTime limit 2s
t[i] is the temperature on day i. For every day, how many days do you have to wait for a warmer temperature? Print 0 if no warmer day comes.
Input:
- line 1:
n - line 2:
ntemperatures
Output: n numbers on one line.
Constraints: 1 ≤ n ≤ 10⁵, 30 ≤ t[i] ≤ 100.
Think about it: keep a stack of days that are still waiting for a warmer day; their temperatures are decreasing from bottom to top. When a warmer day arrives, it answers every colder day on top of the stack. Each day is pushed and popped once — O(n).
Sample input 1
8 73 74 75 71 69 72 76 73
Sample output 1
1 1 4 2 1 1 0 0
Sample input 2
4 30 40 50 60
Sample output 2
1 1 1 0
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).