Taro Logo

Daily Temperatures

Medium
Apple logo
Apple
1 view
Topics:
ArraysStacks

You are given an array of integers called temperatures that represents the daily temperatures. Your task is to return an array called 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]

Explanation:

  • Day 0 (temperature 73): The next warmer day is Day 1 (temperature 74), so the answer is 1.
  • Day 1 (temperature 74): The next warmer day is Day 2 (temperature 75), so the answer is 1.
  • Day 2 (temperature 75): The next warmer day is Day 6 (temperature 76), so the answer is 4.
  • Day 3 (temperature 71): The next warmer day is Day 5 (temperature 72), so the answer is 2.
  • Day 4 (temperature 69): The next warmer day is Day 5 (temperature 72), so the answer is 1.
  • Day 5 (temperature 72): The next warmer day is Day 6 (temperature 76), so the answer is 1.
  • Day 6 (temperature 76): There is no warmer day in the future, so the answer is 0.
  • Day 7 (temperature 73): There is no warmer day in the future, so the answer is 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]

How would you implement an algorithm to solve this problem efficiently? Consider the time and space complexity of your solution.

Solution


Brute Force Solution

A naive approach to solve this problem is to iterate through the temperatures array. For each day, we iterate through the remaining days to find the next warmer day. If we find a warmer day, we record the number of days we had to wait. If we don't find a warmer day, we record 0.

def dailyTemperatures_brute_force(temperatures):
    n = len(temperatures)
    answer = [0] * n

    for i in range(n):
        for j in range(i + 1, n):
            if temperatures[j] > temperatures[i]:
                answer[i] = j - i
                break
    return answer

Time Complexity

The time complexity of this approach is O(n^2) because, in the worst case, we might need to compare each element with every other element in the array.

Space Complexity

The space complexity is O(n) because we use an additional array, answer, of size n to store the results.

Optimal Solution (Using Stack)

We can use a stack to solve this problem in O(n) time. The idea is to iterate through the temperatures array and maintain a stack of indices. The stack stores the indices of days for which we haven't found a warmer day yet. When we encounter a day with a warmer temperature than the temperature at the index at the top of the stack, we pop the index from the stack and update the corresponding value in the answer array with the number of days we had to wait. We continue popping from the stack until the stack is empty or the current temperature is not greater than the temperature at the index at the top of the stack. Finally, we push the current index onto the stack.

def dailyTemperatures(temperatures):
    n = len(temperatures)
    answer = [0] * n
    stack = []

    for i in range(n):
        while stack and temperatures[i] > temperatures[stack[-1]]:
            index = stack.pop()
            answer[index] = i - index
        stack.append(i)

    return answer

Time Complexity

The time complexity of this approach is O(n) because each element is pushed onto the stack and popped from the stack at most once.

Space Complexity

The space complexity is O(n) because, in the worst case, the stack might contain all the indices of the temperatures array.

Edge Cases

  • Empty input array: The code should handle an empty input array gracefully. Although the problem statement indicates that the input array will have at least one element, handling an empty array would make the solution more robust.
  • Decreasing temperatures: If the temperatures are monotonically decreasing, the output array should contain all zeros, as there is no warmer day for any day.
  • Increasing temperatures: If the temperatures are monotonically increasing, the output array should contain all ones except the last element, which should be zero.
  • All temperatures are the same: If all the temperatures are the same, the output array should contain all zeros.