Daily Temperatures
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature.
Examples
temperatures = [73,74,75,71,69,72,76,73]
[1,1,4,2,1,1,0,0]
Day 0 (73): next warmer is day 1 (74), wait 1 day.
Constraints
- •
1 <= temperatures.length <= 10^5 - •
30 <= temperatures[i] <= 100
Approaches
For each day, scan forward to find the next warmer day.
def daily_temperatures(temperatures):
result = [0] * len(temperatures)
for i in range(len(temperatures)):
for j in range(i + 1, len(temperatures)):
if temperatures[j] > temperatures[i]:
result[i] = j - i
break
return resultUse a stack to keep indices of days with decreasing temperatures.
def daily_temperatures(temperatures):
result = [0] * len(temperatures)
stack = []
for i, temp in enumerate(temperatures):
while stack and temperatures[stack[-1]] < temp:
prev_index = stack.pop()
result[prev_index] = i - prev_index
stack.append(i)
return resultTraverse from right to left using a stack.
Diagram
def daily_temperatures(temperatures):
n = len(temperatures)
result = [0] * n
stack = []
for i in range(n - 1, -1, -1):
while stack and temperatures[stack[-1]] <= temperatures[i]:
stack.pop()
if stack:
result[i] = stack[-1] - i
stack.append(i)
return resultComplexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| Brute Force | O(n^2) | O(1) | For each day, scan forward to find the next warmer day. |
| Monotonic Stack | O(n) | O(n) | Use a stack to keep indices of days with decreasing temperatures. |
| Reverse Traversal | O(n) | O(n) | Traverse from right to left using a stack. |
For each day, scan forward to find the next warmer day.
Use a stack to keep indices of days with decreasing temperatures.
Traverse from right to left using a stack.
Common Mistakes
Using a stack that stores values instead of indices
Not popping elements that are less than or equal to the current temperature
Forgetting to initialize the result array with zeros