Daily Temperatures

Program for Printing Daily Temperatures Problem

You are given an array of integers temperatures, where each element temperatures[i] represents the temperature on the i-th day.

Your task is to return an array result, where each element result[i] indicates the number of days you need to wait after the i-th day for a warmer temperature. If no warmer day exists in the future for the i-th day, set result[i] to 0.

Daily Temperature

Constraints:

  • 1 <= temperatures.length <= 1000.
  • 1 <= temperatures[i] <= 100

Program for Printing Daily Temperatures Solution

Recommendation for Time and Space Complexity –You should aim for a solution as good or better than O(n) time and O(n) space, where n is the size of the input array.

Hints for solving problems

Hint 1 :

A brute force solution would involve iterating through the array with index i and checking how far is the next greater element to the right of i. This would be an O(n^2) solution. Can you think of a better way?

Hint 2 :

Can you consider a reverse approach? For example, in [2, 1, 1, 3], the next greater element for the numbers [2, 1, 1] is 3. Instead of checking for each element individually, can you think of a way where, by standing at the element 3, you compute the result for the elements [2, 1, 1]? Maybe there’s a data structure that is useful here.

Hint 3 :

We can use a stack to maintain indices in a monotonically decreasing order, popping indices where the values are smaller than the current element. This helps us find the result by using the difference between indices while considering the values at those indices. Can you see how the stack is useful?

Hint 4 :

In the array [2, 1, 1, 3], we don’t perform any pop operations while processing [2, 1, 1] because these elements are already in decreasing order. However, when we reach 3, we pop elements from the stack until the top element of the stack is no longer less than the current element. For each popped element, we compute the difference between the indices and store it in the position corresponding to the popped element.

There are mainly 3 approach to solve this problem-

  1. Brute Force Method
  2. Stack Method
  3. Dynamic Programming Method

1. Brute Force Method

For each day, iterate through the subsequent days to find the next warmer temperature, resulting in an O(n^2) time complexity.

  • Time complexity: O(n^2)
  • Space complexity: O(1)

Code

2. Stack Method

Use a stack to keep track of indices of days, processing temperatures from right to left to efficiently find the next warmer day, achieving O(n) time complexity.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

3. Dynamic Programming Method

Maintain an array to track the closest index of warmer temperatures by updating results based on future days, balancing between time and space efficiency.

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

More Articles