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 <= 105
30 <= temperatures[i] <= 100
This problem asks us to find, for each day, the number of days we need to wait until a warmer temperature arrives. We can efficiently solve this using a monotonic stack.
Approach: Monotonic Stack
A monotonic stack (in this case, a decreasing stack) is ideal because it keeps track of indices of days with decreasing temperatures. When we encounter a warmer day, we can easily determine the waiting period for all previous cooler days stored in the stack.
Algorithm:
Initialization: Create an empty stack stk
to store indices of days and an array ans
of the same size as temperatures
initialized with zeros. This ans
array will hold our results.
Iteration: Iterate through the temperatures
array from right to left (this is crucial for efficiently finding the next warmer day).
Stack Processing: For each day i
:
temperatures[stk.top()]
) is less than or equal to the current day's temperature (temperatures[i]
):
i
represents the waiting period. Update ans
accordingly.i
onto the stack. This maintains the decreasing order of temperatures in the stack.Return: After iterating through all days, ans
contains the waiting periods for each day. Return ans
.
Time and Space Complexity:
temperatures
array. Each element is pushed and popped at most once from the stack.Code Examples (with detailed comments):
Several code examples in various languages are presented below, showcasing the implementation of this algorithm. Each example follows the algorithm steps explained above.
Python:
def dailyTemperatures(temperatures):
n = len(temperatures)
ans = [0] * n # Initialize result array with zeros
stk = [] # Initialize an empty stack
for i in range(n - 1, -1, -1): # Iterate from right to left
while stk and temperatures[stk[-1]] <= temperatures[i]: # While stack not empty and top element <= current element
stk.pop() # Pop the smaller temperature indices
if stk: # If stack is not empty after popping
ans[i] = stk[-1] - i # Waiting period = index difference
stk.append(i) # Push the current index onto stack
return ans
Java:
import java.util.Deque;
import java.util.ArrayDeque;
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
int[] ans = new int[n];
Deque<Integer> stk = new ArrayDeque<>();
for (int i = n - 1; i >= 0; i--) { // Iterate from right to left
while (!stk.isEmpty() && temperatures[stk.peek()] <= temperatures[i]) { // Stack processing
stk.pop();
}
if (!stk.isEmpty()) {
ans[i] = stk.peek() - i;
}
stk.push(i); // Push index to stack
}
return ans;
}
}
(Similar code structures would be used for C++, JavaScript, Go, TypeScript, and Rust, following the same algorithmic principles).
This detailed explanation and diverse code examples should provide a comprehensive understanding of solving the Daily Temperatures problem using the efficient monotonic stack approach. Remember that the key to this solution lies in the right-to-left traversal and the maintenance of a decreasing monotonic stack.