Taro Logo

Daily Temperatures

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+28
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.5K views
Topics:
ArraysStacks

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected output when there is no warmer day in the future, and does our problem description's instruction of returning zero apply to all such cases?
  2. Can the input array contain negative temperature values or just positive integers, and what is the expected data type and range for these temperatures?
  3. How should we handle duplicate temperatures in the array? Specifically, if today's temperature is equal to a future day's temperature, does that count as 'warmer'?
  4. What is the maximum expected length of the input array (e.g., up to $10^5$ elements) so that I can choose the appropriate time complexity?
  5. If the input array is empty or contains only a single element, what should be the expected return value?

Brute Force Solution

Approach

The brute force approach to solving the daily temperatures problem involves checking every single day against all the future days that follow it. For each day on your calendar, you look ahead one day at a time until you finally spot a day that is warmer.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the very first day on your list.
  2. Look at the day immediately following it to see if it is warmer.
  3. If it is not warmer, look at the next day after that, and keep looking forward one by one until you find a day that is warmer.
  4. Count how many days you had to look forward to find that warmer day.
  5. If you reach the end of your list and never find a warmer day, note that you had to wait forever.
  6. Move on to the second day on your list and repeat the exact same process of looking ahead one day at a time.
  7. Continue this process for every single day on the list until every day has been paired with its wait time for a warmer day.

Code Implementation

def daily_temperatures(temperature_list):
    answer_list = [0] * len(temperature_list)

    # Iterate through every single day to establish a baseline for finding future warmer temperatures
    for current_day_index in range(len(temperature_list)):
        day_counter = 1
        target_day_index = current_day_index + 1
        
        # Scan forward day by day until a warmer temperature is found or the end of the list is reached
        while target_day_index < len(temperature_list):
            if temperature_list[target_day_index] > temperature_list[current_day_index]:
                answer_list[current_day_index] = day_counter
                break

            day_counter += 1
            target_day_index += 1
            
        # If no warmer day exists in the future, the answer remains zero as initialized

    return answer_list

Big(O) Analysis

Time Complexity
O(n²) – For each of the n days in the input array, we potentially iterate through all the remaining future days to find a warmer temperature. Since the first day might require checking (n-1) subsequent days, the second day (n-2) days, and so on, the total number of operations approximates n * n / 2. Dropping the constant factor gives a final worst-case time complexity of O(n²).
Space Complexity
O(1) – The brute force algorithm described processes each day by looking ahead iteratively without utilizing any additional data structures like stacks, hash maps, or auxiliary arrays. The only memory consumed consists of a few primitive variables used for tracking indices and loop counters, which require constant extra space regardless of the input size. Because no extra memory scales with the number of days N, the auxiliary space complexity remains strictly constant.

Optimal Solution

Approach

Instead of checking every future day for every single point in time, we can look at the temperatures from right to left while keeping a handy waiting room for days that haven't found their warmer day yet. Whenever we see a warmer temperature, we match it up with the waiting days that are colder, figuring out their wait time instantly.

Here's how the algorithm would work step-by-step:

  1. Imagine walking backward through a timeline of daily temperatures, starting from the very last day and moving toward the first.
  2. Keep a mental holding area to track days that are still waiting to find a future day with a higher temperature.
  3. As you look at each new temperature from the past, compare it with the days currently waiting in your holding area.
  4. If the current temperature is warmer than the days waiting in your holding area, those waiting days have finally found their answer.
  5. Calculate the exact wait time for those resolved days by seeing how far apart they are on the timeline, and remove them from the holding area.
  6. Once you have cleared out all the colder days, add the current day to the holding area so it can wait for its own warmer day in the future.
  7. Continue this process all the way to the very first day, ensuring every day quickly finds its answer without needing to repeatedly search the entire future one by one.

Code Implementation

def daily_temperatures(temperature_list):
    total_days = len(temperature_list)
    answer_list = [0] * total_days
    waiting_room = []

    # Traverse backwards to instantly resolve future warmer days without redundant checks.
    for current_day_index in range(total_days - 1, -1, -1):
        current_temperature = temperature_list[current_day_index]

        # Pop colder days from the stack since they have found their warmer future day.
        while waiting_room and temperature_list[waiting_room[-1]] <= current_temperature:
            waiting_room.pop()

        # If days remain in the stack, the top one represents the next warmer temperature.
        if waiting_room:
            answer_list[current_day_index] = waiting_room[-1] - current_day_index

        waiting_room.append(current_day_index)

    return answer_list

Big(O) Analysis

Time Complexity
O(n) – The input size n represents the total number of days and temperatures in the array. As we iterate backward from the last day to the first, each of the n indices is pushed onto and popped from the stack at most once. Even though there is a while loop inside the main loop to pop colder days, every element enters and leaves the stack a constant number of times. This bounds the total operations to approximately 2n steps, which simplifies to the final Big O time complexity of O(n).
Space Complexity
O(n) – The auxiliary space complexity is driven by the mental holding area described in the plain English steps, which is implemented as a monotonic stack storing indices of the temperatures. In the worst-case scenario where temperatures continuously decrease, every single day gets pushed onto this stack. Therefore, the stack grows linearly with the input size N, requiring up to N elements of extra memory.

Edge Cases

Empty or null input array
How to Handle:
Return an empty array immediately to prevent null pointer exceptions or out-of-bounds errors.
Single-element array
How to Handle:
Return an array containing a single zero since there are no future days to wait for.
Temperatures in strictly decreasing order
How to Handle:
The monotonic stack naturally leaves these elements waiting indefinitely, resulting in an array of all zeros.
Temperatures in strictly increasing order
How to Handle:
Each element will immediately pop the stack, resulting in an array where every day has a wait time of exactly one.
All identical temperature values
How to Handle:
The stack will accumulate all indices without finding a greater value, leading to an array of all zeros.
Negative temperatures and mixed zero values
How to Handle:
Since the logic relies entirely on relative numerical comparisons rather than absolute magnitudes, negative values and zeros are processed seamlessly.
Maximum-sized input arrays near constraints
How to Handle:
The monotonic stack processes each element at most twice, ensuring optimal O(N) time complexity and preventing timeout issues.
Extreme boundary values for temperatures
How to Handle:
Using standard 32-bit integers prevents overflow issues since we only store array indices and compare values.
0/75 completed