
Problem Statement
In this problem statement, you are provided with an array temperatures
where each element in the array represents the temperature of a day. The task is to determine the number of days one has to wait for a temperature that's warmer than the current day's temperature. The result should be an array answer
where answer[i]
indicates the number of days to wait after day i
to experience a warmer day. If no such future day is warmer, then answer[i]
should be set to 0
. The challenge is to efficiently navigate through the temperatures
array and compute the required days for each temperature.
Examples
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
Approach and Intuition
To solve this problem efficiently while keeping the time complexity in check, we can employ a stack data structure to help trace days with warmer temperatures dynamically as we iterate through the list:
- Initialize an empty stack and an array
answer
of the same length astemperatures
, filled initially with zeros. - Iterate through the
temperatures
list using an indexi
:- While the stack is not empty and the current temperature
temperatures[i]
is greater than the temperature at the index represented by the top of the stack (temperatures[stack[-1]]
):- Pop the index from the stack and calculate the difference between the current index
i
and the popped index. This represents how many days the warmer temperature was awaited. - Update
answer
at the popped index with this difference.
- Pop the index from the stack and calculate the difference between the current index
- Push the current index
i
onto the stack.
- While the stack is not empty and the current temperature
- The stack helps in remembering indices of temperatures for which we haven't yet found a warmer day. The usage of the stack ensures that each index is pushed and popped only once, leading to a time complexity of O(n).
Examples Explained:
- For
temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
, the process is as follows:- Start with day 0 (73°F). It's warmer the very next day (74°F), hence
answer[0] = 1
. - For day 2 (75°F), it takes 4 more days until it reaches 76°F, so
answer[2] = 4
. - Days that are at the end of the array or do not have any warmer days following them will record a
0
, such asanswer[6]
andanswer[7]
since 76°F and 73°F are the last temperatures without any warmer days ahead.
- Start with day 0 (73°F). It's warmer the very next day (74°F), hence
This approach ensures that for each day we are capturing the wait-time efficiently for a warmer day or establishing that no warmer day exists.
Solutions
- Java
- Python
class Solution {
public int[] forecastHeating(int[] temps) {
int len = temps.length;
int maxTemp = 0;
int result[] = new int[len];
for (int i = len - 1; i >= 0; i--) {
int tempToday = temps[i];
if (tempToday >= maxTemp) {
maxTemp = tempToday;
continue;
}
int delay = 1;
while (temps[i + delay] <= tempToday) {
// Update delay based on previously computed results
delay += result[i + delay];
}
result[i] = delay;
}
return result;
}
}
The function forecastHeating
in Java is designed to solve the problem of determining how many days you must wait for a warmer temperature, given an array of daily temperatures. The process involves iterating backwards through the array of temperatures and using a greedy algorithm to compute the waiting days efficiently.
Initialize an integer array
result
of the same length as the inputtemps
to store the number of days until a warmer day occurs for each temperature intemps
.Start from the last day, working backwards, to utilize previously computed results for future computations.
For every day, compare the temperature to the maximum temperature observed so far. If it is equal or greater, update the maximum temperature and move on since no future temperature would be warmer.
If a warmer day in the future exists, calculate the number of days until that day by using a while loop which increments through subsequent days. The loop utilizes
result
from future days to skip over days that don't need individual checking, speeding up the process by avoiding unnecessary comparisons.Store the required delay in the
result
array for each day.
Given this methodology, the function efficiently calculates and returns an array indicating the number of days one would wait for a warmer temperature for each day given in temps
. The use of backward traversal and leveraging previously calculated values minimizes redundant checks and optimizes performance.
class Solution:
def findWarmerDays(self, temps: List[int]) -> List[int]:
len_temps = len(temps)
max_temp = 0
days_until_warmer = [0] * len_temps
for today in range(len_temps - 1, -1, -1):
current_temp = temps[today]
if current_temp >= max_temp:
max_temp = current_temp
continue
days_offset = 1
while temps[today + days_offset] <= current_temp:
# Jump to next warmer day using previously stored results
days_offset += days_until_warmer[today + days_offset]
days_until_warmer[today] = days_offset
return days_until_warmer
The given Python code provides a solution for finding the number of days one must wait until experiencing a warmer temperature based on a list of daily temperatures. The function implements an efficient approach that traverses the list from the last day to the first, using a stack data structure implicitly to track the temperatures and their indices.
Understand the steps and principles behind the implementation:
Initialize
len_temps
to store the length of the input listtemps
.Set
max_temp
to zero to hold the maximum temperature observed as the list is processed from the end.Create a list
days_until_warmer
of the same length astemps
, initialized with zeros. This list will eventually contain the result, showing for each day how many days one must wait until a warmer temperature.Loop through the list in reverse using a for loop (starting from the last element and moving to the first). This reverse loop helps in building the solution from known future values.
- For each day, compare the day's temperature to
max_temp
. - If the current day’s temperature is equal or greater than
max_temp
, updatemax_temp
to the current day's temperature. There is no need for further checks as no warmer days exist after this point. - If the current day's temperature is less than
max_temp
, initializedays_offset
to 1. This variable helps to find the next warmer day.- Use a while loop to skip to the next known warmer days using the results already stored in
days_until_warmer
. - Increment
days_offset
by the values stored indays_until_warmer
at the appropriate indices, thereby jumping several days ahead in a single step if possible.
- Use a while loop to skip to the next known warmer days using the results already stored in
- Store the final calculated
days_offset
for the current day indays_until_warmer
.
- For each day, compare the day's temperature to
Return the
days_until_warmer
list, which now contains the number of days one must wait for a warmer temperature for each day in the list.
This method optimizes the search for the next warmer day by avoiding the examination of each subsequent day individually through intelligent use of previously computed values, significantly speeding up the process in typical scenarios.
No comments yet.