739. Daily Temperatures LeetCode Solution
In this guide, you will get 739. Daily Temperatures LeetCode Solution with the best time and space complexity. The solution to Daily Temperatures problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Daily Temperatures solution in C++
- Daily Temperatures solution in Java
- Daily Temperatures solution in Python
- Additional Resources
Problem Statement of 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. 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
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
739. Daily Temperatures LeetCode Solution in C++
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
vector<int> ans(temperatures.size());
stack<int> stack; // a decreasing stack
for (int i = 0; i < temperatures.size(); ++i) {
while (!stack.empty() && temperatures[stack.top()] < temperatures[i]) {
const int index = stack.top();
stack.pop();
ans[index] = i - index;
}
stack.push(i);
}
return ans;
}
};
/* code provided by PROGIEZ */
739. Daily Temperatures LeetCode Solution in Java
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] ans = new int[temperatures.length];
Deque<Integer> stack = new ArrayDeque<>(); // a decreasing stack
for (int i = 0; i < temperatures.length; ++i) {
while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
final int index = stack.pop();
ans[index] = i - index;
}
stack.push(i);
}
return ans;
}
}
// code provided by PROGIEZ
739. Daily Temperatures LeetCode Solution in Python
class Solution:
def dailyTemperatures(self, temperatures: list[int]) -> list[int]:
ans = [0] * len(temperatures)
stack = [] # a decreasing stack
for i, temperature in enumerate(temperatures):
while stack and temperature > temperatures[stack[-1]]:
index = stack.pop()
ans[index] = i - index
stack.append(i)
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.