class Solution(object): def dailyTemperatures(self, temperatures): """ :type temperatures: List[int] :rtype: List[int] """ # Two pointer method, timed out O(n^2) # count = 0 # warmer_days = [] # l = 0 # r = 1 # while l < r: # # print(r) # if r == len(temperatures)-1: # if l != len(temperatures)-2: # if temperatures[r] > temperatures[l]: # count += 1 # warmer_days.append(count) # else: # warmer_days.append(0) # l += 1 # r = l + 1 # count = 0 # else: # if temperatures[r] > temperatures[l]: # count += 1 # warmer_days.append(count) # else: # warmer_days.append(0) # break # elif temperatures[r] > temperatures[l]: # count += 1 # warmer_days.append(count) # count = 0 # l += 1 # r = l + 1 # else: # r += 1 # count += 1 # warmer_days.append(0) # return warmer_days # Stack Method res = [0] * len(temperatures) stack = [] # contains pair of [temp, index] for i, t in enumerate(temperatures): #looping through temperatures array and their index while stack and t > stack[-1][0]: # is our stack empty and is our temperature greater than the top of our stack stackT, stackInd = stack.pop() res[stackInd] = (i - stackInd) # compute the days it took us to find a higher temperature stack.append((t,i)) # append to the stack the temperature and index return res obj = Solution() print(obj.dailyTemperatures([73,74,75,71,69,72,76,73])) # [1,1,4,2,1,1,0,0] # print(obj.dailyTemperatures([30,40,50,60])) # [1,1,1,0] # print(obj.dailyTemperatures([55,38,53,81,61,93,97,32,43,78])) # [3,1,1,2,1,1,0,1,1,0] # print(obj.dailyTemperatures([77,77,77,77,77,41,77,41,41,77])) # [0,0,0,0,0,1,0,2,1,0]