LeetCode 739: Daily Temperatures

class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
#initialize the stack
stack = []
#initialize the result, it has the same length as temperature array as well.
n = len(temperatures)
result = [0] * n

# We choose to iterate from 1 to n since 0th element won't be greater than 0th
for i in range(1,n):

# Check if the current temperature
#is larger than the stack
# top's index's corresponding temperature
if temperatures[i] > temperatures[stack[-1]]:
# If so, we iteratively pop the indices off until we found a
# index that is larger than current temperature.
while stack and temperatures[i] > temperatures[stack[-1]]:
idx = stack.pop()
result[idx] = i - idx

# Add current temperatures' index to stack since we haven't iterate
# to a larger temperature yet.

return result



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store