Daily Temperatures in Python

C++Server Side ProgrammingProgramming

Suppose we have a list of daily temperatures T, we have to return a list such that, for each day in the input, shows how many days we would have to wait until a warmer temperature. If there is no future day for which this is possible, store 0 instead. For example, if T = [73, 74, 75, 71, 69, 72, 76, 73], output will be [1, 1, 4, 2, 1, 1, 0, 0].

To solve this, we will follow these steps −

  • ans := an array of size same as T, and fill this with 0
  • define one stack, and insert 0 into the stack, and i := 1
  • while i < length of T
    • while stack element count is not 0 and T[i] > T[stack top element]
      • index := stack top element
      • ans[index] := i – index
      • delete top element from stack
    • if length of stack is 0 or T[i] <= T[stack top element]
      • insert i into stack
    • increase i by 1
  • return ans

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def dailyTemperatures(self, T):
      ans = [0 for i in range(len(T))]
      stack = []
      stack.append(0)
      i=1
      while i <len(T):
         while len(stack) and T[i]>T[stack[-1]]:
            index = stack[-1]
            ans[index] = i-index
            stack.pop()
         if not len(stack) or T[i]<=T[stack[-1]]:
            stack.append(i)
         i+=1
      return ans
ob1 = Solution()
print(ob1.dailyTemperatures([73,74,75,71,69,72,76,73]))

Input

[73,74,75,71,69,72,76,73]

Output

[1, 1, 4, 2, 1, 1, 0, 0]
raja
Published on 27-Feb-2020 11:02:25
Advertisements