Daily Temperatures — Day 69(Python)

Image for post
Image for post
Photo by Isaac Smith on Unsplash

Today’s question is a medium tagged question in Leetcode. It is a common question among tech interviewers. Let us look into the question.

739. Daily Temperatures

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

One of the easiest ways to solve this problem is by taking each number, running a loop to find a number that is greater than the current number, and then finding the difference between the indexes of both the numbers.

Let us look into the code snippet.

Complexity analysis.

Time Complexity

In the worst-case scenario, if the given array is monotonically decreasing, then we will be running the loop for N² times. Hence the time complexity is O(N²), where N is the number of elements in the array.

Space Complexity.

We are not storing any intermediary results in any data structures, hence space complexity is O(1).

If we try to run this code on leetcode, we will get a time limit exceeded error. We would need to improve the time complexity. Can we try using any extra data structure to solve this problem?

We can improve the time complexity by making use of a stack. In the stack, we will be storing the temperature and its index in the input array. We can run the loop that starts from the end of the input array. Each time, we will compare the current temperature and the topmost temperature in the stack. If the current temperature is higher or equal to the topmost temperature in the stack, we will keep popping the values from the stack.

If the stack is empty, the output will be 0 for that temperature else we will be storing the difference of index between current temperature and topmost element in the stack.

Complexity analysis.

Time Complexity

The time complexity for this algorithm is O(N).

Space Complexity.

The space complexity for this algorithm is O(N).

Software Engineer. Find me @ www.linkedin.com/in/annamariya-jt

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store