- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Daily Temperatures in Python
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
- while stack element count is not 0 and T[i] > T[stack top element]
- return ans
Example(Python)
Let us see the following implementation to get a better understanding −
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]
Advertisements