Daily Temperatures
In this tutorial, we are going to solve a leetcode problem, Daily Temperatures in python.
Task:
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:
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
lst = [0] * len(temperatures)
stack = []
for idx in range(len(temperatures)):
while stack and temperatures[stack[-1]] < temperatures[idx]:
lst[stack[-1]] = idx - stack[-1]
stack.pop()
stack.append(idx)
return lst
Steps:
step1: In this problem, we are going to make a list of zeros of length equal to temperatures.
step2: Then, we create empty list stack and loop opver the indexs of temperatures.
step3: Inside the for loop, there is another while loop which runs till stack and element at temperatures[stack[-1]] < temperatures[idx[.
step4: Inside the while loop, we add the index difference i.e. idx - stack[-1] at lst[stacl[-1]].
step5: Now, we pop the stack and append the idx after the while loop for next iteration and return the lst.