#739
Daily Temperatures
MediumApproaches
💡
Intuition
Time O(n²)Space O(1)
The brute force approach involves checking each day's temperature against all future days to find the next warmer day. This is straightforward but inefficient for larger arrays.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an answer array of the same length as temperatures with all zeros.
- 2Step 2: For each day, iterate through the subsequent days to find the first day with a warmer temperature.
- 3Step 3: If a warmer temperature is found, calculate the difference in days and store it in the answer array.
solution.py9 lines
1def dailyTemperatures(temperatures):
2 n = len(temperatures)
3 answer = [0] * n
4 for i in range(n):
5 for j in range(i + 1, n):
6 if temperatures[j] > temperatures[i]:
7 answer[i] = j - i
8 break
9 return answerℹ
Complexity note: The time complexity is O(n²) because for each day, we may potentially check all subsequent days. The space complexity is O(1) since we are using only a fixed amount of extra space.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.