739. Daily Temperatures
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the number of days one has to wait for a warmer temperature for each day in a given list of daily temperatures. If no such warmer day exists in the future, the wait is 0. This is a classic example of the "Next Greater Element" problem, where for each element in an array, we need to find the first element to its right that is larger.
Solution
Daily Temperatures in Python
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
# Initialize the answer array with 0s.
# This is the default value if no warmer day is found.
answer = [0] * n
# A stack to store indices of days. It maintains indices of days
# with monotonically decreasing temperatures.
stack = []
for i, temp in enumerate(temperatures):
# While the stack is not empty and the current temperature is warmer
# than the temperature of the day at the top of the stack.
while stack and temperatures[stack[-1]] < temp:
# This means we found a warmer day for the day at stack[-1].
prev_index = stack.pop()
# Calculate the number of days to wait.
answer[prev_index] = i - prev_index
# Push the current day's index onto the stack.
stack.append(i)
return answer
Daily Temperatures in Java
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
// The answer array, initialized to 0s by default in Java.
int[] answer = new int[n];
// A stack to store indices of days. It maintains indices of days
// with monotonically decreasing temperatures.
// ArrayDeque is generally more efficient than Stack.
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
// While the stack is not empty and the current day's temperature
// is warmer than the temperature of the day at the top of the stack.
while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
// This means we found a warmer day for the day at stack.peek().
int prevIndex = stack.pop();
// Calculate the number of days to wait.
answer[prevIndex] = i - prevIndex;
}
// Push the current day's index onto the stack.
stack.push(i);
}
return answer;
}
}
Daily Temperatures in C++
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
// Initialize the answer vector with 0s.
// This is the default value if no warmer day is found.
vector<int> answer(n, 0);
// A stack to store indices of days. It maintains indices of days
// with monotonically decreasing temperatures.
stack<int> s;
for (int i = 0; i < n; ++i) {
// While the stack is not empty and the current day's temperature
// is warmer than the temperature of the day at the top of the stack.
while (!s.empty() && temperatures[s.top()] < temperatures[i]) {
// This means we found a warmer day for the day at s.top().
int prev_index = s.top();
s.pop();
// Calculate the number of days to wait.
answer[prev_index] = i - prev_index;
}
// Push the current day's index onto the stack.
s.push(i);
}
return answer;
}
};
Daily Temperatures in TypeScript
function dailyTemperatures(temperatures: number[]): number[] {
const n = temperatures.length;
// Initialize the answer array with 0s.
// This is the default value if no warmer day is found.
const answer = new Array(n).fill(0);
// A stack to store indices of days. It maintains indices of days
// with monotonically decreasing temperatures.
const stack: number[] = [];
for (let i = 0; i < n; i++) {
// While the stack is not empty and the current day's temperature
// is warmer than the temperature of the day at the top of the stack.
while (stack.length > 0 && temperatures[stack[stack.length - 1]] < temperatures[i]) {
// This means we found a warmer day for the day at the top of the stack.
// The non-null assertion `!` is used because the loop condition guarantees the stack is not empty.
const prevIndex = stack.pop()!;
// Calculate the number of days to wait.
answer[prevIndex] = i - prevIndex;
}
// Push the current day's index onto the stack.
stack.push(i);
}
return answer;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.