Daily Temperatures Solution
Anonymous User
421
def dailyTemperatures(self, temperatures):
    #length of temperatures 
    l = len(temperatures)
    
    #initilialize list of 0s
    days = [0] * l
    
    #initialize stack
    stack = []
    
    #for loop to go through each element
    for x in range(len(temperatures)):
        
        #going throught the stack 
        while len(stack):
            if stack[-1][0] < temperatures[x]:
                element, index  = stack.pop()
                days[index] = x - index
            else: 
                break
        
        #appending the temperature and amount of index to stack 
        stack.append((temperatures[x], x))
       
        
    return days
            

'''
In this code, I use a monotonic stack in order to solve the problem. I first have a variable to hold the length of the temperatures array. I also initialize a stack to hold my information as well as a list with 0's to hold default values for if there is no amount of days to wait for a warmer temperature. In the for loop, I go through each index of the temperatures array. I then go through my stack, which holds both the index and element(temp) of each day. The while lops first finds the next warm day and then changes the value of the corresponding spot in the days list to the amount of indices away until the increase in temperature happens. Then, a new temperature and index is appended to the stack. The days list is returned and holds the amount of days until the next warm day.

Comments (1)