0739-daily-temperatures¶
Try it on leetcode
Description¶
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. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73] Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60] Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90] Output: [1,1,0]
Constraints:
1 <= temperatures.length <= 10530 <= temperatures[i] <= 100
Solution(Python)¶
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
return self.monotonic_stack(temperatures)
# bruteforce
# as we read through each temperature
# i will count until something is greater
# Time Complexity: O(n^2)
# Space complexity: O(1)
# montonic stack
# use stack to keep track of previous temperature with lower index
# once i found that my current temparture is greater then i will store the result
#
def monotonic_stack(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
# stack empty
stack = []
# result array with zero
res = [0] * n
# loop through
for i in range(n):
# compare the temp index in the stac k with current temperature if greater then update the result of stack
while stack and temperatures[i] > temperatures[stack[-1]]:
res[stack[-1]] = i - stack[-1]
# pop it
stack.pop()
# append my current index to stack
stack.append(i)
return res