Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Stack

Daily Temperatures

medium

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

Given an integer array temps representing daily temperatures, write a function to calculate the number of days one has to wait for a warmer temperature after each given day. The function should return an array answer where answer[i] represents the wait time for a warmer day after the ith day. If no warmer day is expected in the future, set answer[i] to 0.

Inputs:

temps = [65, 70, 68, 60, 55, 75, 80, 74]

Output:

[1,4,3,2,1,1,0,0]

Explanation

This question uses a monotonically decreasing stack to find the next greatest temperature for each day in O(n) time, compared to the O(n2) time of the brute-force approach.
A monotonically decreasing stack stores indices, where the temperature values at those indices decrease from bottom to top of the stack. When pushing an index onto this stack, the temperature at that index must be smaller than the temperatures at all other indices currently on the stack.
73727268stack
A montonically decreasing stack
First, we initialize our stack and our results array. Our stack holds indices of the temperatures in the input array that are waiting for a higher temperature, and our results array holds the number of days we have to wait after the ith day to get a warmer temperature.
Visualization
Python
Language
def dailyTemperatures(temps):
n = len(temps)
result = [0] * n
stack = []
for i in range(n):
while stack and temps[i] > temps[stack[-1]]:
idx = stack.pop()
result[idx] = i - idx
stack.append(i)
return result
737475716972767301234567

daily temperatures

0 / 1

Next, we iterate over each index in the array. For each index, we get the current temperature of that index, and compare it to the temperature of the top index in the stack.

Pushing to the Stack

If the current temperature is less than the top temperature in the stack (or if the stack is empty), we push the current index onto the stack to indicate that we are waiting to find a greater temperature for that index.
Visualization
Python
Language
def dailyTemperatures(temps):
n = len(temps)
result = [0] * n
stack = []
for i in range(n):
while stack and temps[i] > temps[stack[-1]]:
idx = stack.pop()
result[idx] = i - idx
stack.append(i)
return result
7374757169727673012345670000000001234567stack

initialize variables

0 / 2

Pushing index 0 to the stack

Popping from the Stack

When the current temperature is greater than the top temperature in the stack, we have found the next highest temperature for not only the top index in the stack, but potentially other indices in the stack as well, which we can efficiently process due to the monotonically decreasing stack.
We first pop the top index from the stack and calculate the number of days we had to wait for that popped index to find a warmer temperature (current index minus the popped index), and store that number in the results array at the index of the popped element. To account for the fact that the current temperature might be the next greatest temperature for multiple indicies, we repeat this process in a while loop until the current temperature is less than the top temperature in the stack, or until the stack is empty.
After that is done, we push the current index onto the stack to indicate that we have not yet found the next greatest temperature for the current index.
Visualization
Python
Language
def dailyTemperatures(temps):
n = len(temps)
result = [0] * n
stack = []
for i in range(n):
while stack and temps[i] > temps[stack[-1]]:
idx = stack.pop()
result[idx] = i - idx
stack.append(i)
return result
737475716972767301234567i00000000012345670stack

i = 1

0 / 2

Popping index 0 from the stack
Visualization
Python
Language
def dailyTemperatures(temps):
n = len(temps)
result = [0] * n
stack = []
for i in range(n):
while stack and temps[i] > temps[stack[-1]]:
idx = stack.pop()
result[idx] = i - idx
stack.append(i)
return result
737475716972767301234567i110000000123456723stack

push to stack

0 / 9

Popping multiple indexes from the stack. 75 is a higher temperature for 55, 60, 68 and 70.
This continues until we have iterated over the entire input array. At the end, we return the results array.
Efficency of the Monotonically Decreasing Stack
This is more efficient than the brute-force approach because it reduces the number of comparisons we have to make. For example, consider the state of the stack when we are at the 3rd index in the input array.
Visualization
Python
Language
def dailyTemperatures(temps):
n = len(temps)
result = [0] * n
stack = []
for i in range(n):
while stack and temps[i] > temps[stack[-1]]:
idx = stack.pop()
result[idx] = i - idx
stack.append(i)
return result
737475716972767301234567i1100000001234567stack

result[1] = 2 - 1

0 / 1

Because the stack is monotonically decreasing, we only have to compare the temperature at i (60) to the temperature of the index at the top of the stack (68), to know that it cannot be a higher temperature for the other remaining items on the stack (70), which avoids a comparision between 60 and 70. But in the brute-force approach, 60 and 70 are compared when finding the next greatest temperature after 70.

Solution

Visualization
Python
Language
Try these examples:
def dailyTemperatures(temps):
n = len(temps)
result = [0] * n
stack = []
for i in range(n):
while stack and temps[i] > temps[stack[-1]]:
idx = stack.pop()
result[idx] = i - idx
stack.append(i)
return result
737475716972767301234567

daily temperatures

0 / 30

Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(n) where n is the length of the input array. Each item is pushed and popped from the stack at most once.

Space Complexity: O(n) where n is the length of the input array for the output results array.

Mark as read

Next: Largest Rectangle in Histogram

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Explanation

Solution

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress