You are given an array of integers called temperatures
that represents the daily temperatures. Your task is to return an array called answer
such that answer[i]
is the number of days you have to wait after the i
th 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]
Explanation:
Example 2:
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90]
Output: [1,1,0]
How would you implement an algorithm to solve this problem efficiently? Consider the time and space complexity of your solution.
A naive approach to solve this problem is to iterate through the temperatures
array. For each day, we iterate through the remaining days to find the next warmer day. If we find a warmer day, we record the number of days we had to wait. If we don't find a warmer day, we record 0.
def dailyTemperatures_brute_force(temperatures):
n = len(temperatures)
answer = [0] * n
for i in range(n):
for j in range(i + 1, n):
if temperatures[j] > temperatures[i]:
answer[i] = j - i
break
return answer
The time complexity of this approach is O(n^2) because, in the worst case, we might need to compare each element with every other element in the array.
The space complexity is O(n) because we use an additional array, answer
, of size n to store the results.
We can use a stack to solve this problem in O(n) time. The idea is to iterate through the temperatures
array and maintain a stack of indices. The stack stores the indices of days for which we haven't found a warmer day yet. When we encounter a day with a warmer temperature than the temperature at the index at the top of the stack, we pop the index from the stack and update the corresponding value in the answer
array with the number of days we had to wait. We continue popping from the stack until the stack is empty or the current temperature is not greater than the temperature at the index at the top of the stack. Finally, we push the current index onto the stack.
def dailyTemperatures(temperatures):
n = len(temperatures)
answer = [0] * n
stack = []
for i in range(n):
while stack and temperatures[i] > temperatures[stack[-1]]:
index = stack.pop()
answer[index] = i - index
stack.append(i)
return answer
The time complexity of this approach is O(n) because each element is pushed onto the stack and popped from the stack at most once.
The space complexity is O(n) because, in the worst case, the stack might contain all the indices of the temperatures
array.