Monotonic Stack & Queue
Data StructuresNearest greater/smaller elements and range extremums in linear time
86 problems·2 Easy·50 Medium·34 Hard
Pattern Study Guide & Cheat Sheet▼
Maintain a stack with strictly increasing or decreasing elements to find the Nearest Greater or Smaller Element for all elements in O(N) total time.
Core Invariant: Every element is pushed once and popped at most once. Pushing an element pops all elements that violate monotonicity, meaning the incoming element IS their Next Greater/Smaller answer!
Recognize it (Keywords & Signals)
- Find next greater / next smaller element for each position
- Previous greater element / stock span problems
- Largest rectangle in histogram
- Daily temperatures (number of days until a warmer day)
- Trapping rain water (horizontal bounded bars)
When NOT to use
Need arbitrary lookups across non-monotonic boundaries or dynamic insertions with k-th queries (use Heap or BST).
How to solve (Step-by-step)
- 1.Initialize `stack = []` (store indices to compute distances) and `res = [-1] * n`.
- 2.Iterate `i` from 0 to n - 1 with current value `x = nums[i]`.
- 3.While stack is non-empty and `nums[stack[-1]] < x` (for next greater): pop `idx = stack.pop()`, record `res[idx] = x`.
- 4.Push current index `i` onto stack.
- 5.Elements left in stack have no next greater element (remain -1).
Watch for (Interview Traps)
- Storing values instead of indices (indices allow both value lookup and distance calculation)
- Confusion over `<` vs `<=` (decide whether equal values should pop or remain based on problem statement)
- Circular arrays: forget to iterate `2 * n` with index `i % n`
Next Greater Element (Monotonic Decreasing Stack)
def next_greater_elements(nums: list[int]) -> list[int]:
n = len(nums)
res = [-1] * n
stack = [] # Stores indices of unresolved elements
for i in range(n):
# Pop all elements smaller than current element nums[i]
while stack and nums[i] > nums[stack[-1]]:
popped_idx = stack.pop()
res[popped_idx] = nums[i] # nums[i] is the next greater element!
stack.append(i)
return res- Cost
- O(n) amortized (each index pushed and popped at most once) · O(n) for stack and result array (Avoids O(n^2) nested search for adjacent extremes.)
Canonical problems
#739 Daily Temperatures: Monotonic decreasing stack tracks days until warmer temperature
#84 Largest Rectangle in Histogram: Monotonic increasing stack finds left/right smaller boundaries
#42 Trapping Rain Water: Stack stores decreasing valley bars until bounded by higher right wall
#907 Sum of Subarray Minimums: Find left and right strictly smaller elements for each value
⌘K
Hard·32 companies·Max freq 92%·Acc 50.3%
NeetCode 150NeetCode 150thoughtspot+29
Medium·18 companies·Max freq 80%·Acc 68.7%
SigmoidZeta GlobalServiceNow+15
Hard·18 companies·Max freq 77%·Acc 73.3%
CitigroupWaymoCitigroup+15
Medium·17 companies·Max freq 100%·Acc 57.8%
UberMolocoPhonePe+14
Medium·12 companies·Max freq 90%·Acc 50.7%
Two SigmaMakeMyTripSprinklr+9
Hard·11 companies·Max freq 88%·Acc 69.2%
MathWorksChubbMorgan Stanley+8
Medium·9 companies·Max freq 100%·Acc 38.4%
LiveRampeBayTikTok+6
Medium·9 companies·Max freq 100%·Acc 63.7%
FactSetByteDancePaytm+6
Medium·9 companies·Max freq 97%·Acc 51.4%
razorpayTekionDE Shaw+6
Hard·8 companies·Max freq 100%·Acc 32.9%
DevRevPhonePeGoldman Sachs+5
Hard·8 companies·Max freq 67%·Acc 78.2%
Dream11GoogleSprinklr+5
Easy·7 companies·Max freq 100%·Acc 84.2%
Dream11UberMicrosoft+4
Medium·6 companies·Max freq 38%·Acc 84.4%
AmazonSalesforceMeta+3
Medium·5 companies·Max freq 100%·Acc 51.8%
ZenefitsExpediaSalesforce+2
Hard·5 companies·Max freq 88%·Acc 50.0%
Walmart LabsAmazonMeta+2
Hard·5 companies·Max freq 75%·Acc 52.4%
InfosysMetaAmazon+2
Hard·4 companies·Max freq 100%·Acc 45.8%
instabaseTikTokGoogle+1
Medium·4 companies·Max freq 88%·Acc 67.9%
MathWorksPhonePeBloomberg+1
Medium·4 companies·Max freq 38%·Acc 64.5%
MicrosoftBloombergAmazon+1
Medium·4 companies·Max freq 26%·Acc 71.0%
GoogleBloombergAmazon+1
Medium·4 companies·Max freq 18%·Acc 53.1%
BloombergMetaAmazon+1
Medium·4 companies·Max freq 13%·Acc 58.5%
MetaAmazonMicrosoft+1
Hard·3 companies·Max freq 100%·Acc 24.0%
HuaweiWorldQuantDE Shaw
Hard·3 companies·Max freq 29%·Acc 41.8%
MicrosoftAmazonGoogle
Medium·3 companies·Max freq 28%·Acc 63.8%
UberGoogleMicrosoft
Hard·2 companies·Max freq 100%·Acc 20.7%
PaytmMeta
Medium·2 companies·Max freq 28%·Acc 37.5%
SalesforceGoogle
Hard·2 companies·Max freq 25%·Acc 33.7%
LinkedInAmazon
Hard·2 companies·Max freq 25%·Acc 24.9%
GoogleMicrosoft
Hard·1 companies·Max freq 100%·Acc 40.0%
Deutsche Bank
Medium·1 companies·Max freq 25%·Acc 75.3%
Amazon
# | Problem | Difficulty | Top Companies↓ | Frequency | Acceptance | |
|---|---|---|---|---|---|---|
| #42 | Trapping Rain Water ArrayTwo PointersDynamic ProgrammingStackMonotonic Stack | Hard | 100% | 67.7% | ||
| #239 | Sliding Window Maximum ArrayQueueSliding WindowHeap (Priority Queue)Monotonic QueueRange Minimum/Maximum Query | Hard | 100% | 49.0% | ||
| #735 | Asteroid Collision ArrayStackSimulation | Medium | 100% | 0.5% | ||
| #739 | Daily Temperatures ArrayStackMonotonic Stack | Medium | 100% | 68.9% | ||
| #84 | Largest Rectangle in Histogram ArrayStackMonotonic StackRange Minimum/Maximum Query | Hard | 92% | 50.3% | ||
| #402 | Medium | 100% | 37.2% | |||
| #503 | Next Greater Element II ArrayStackMonotonic Stack | Medium | 80% | 68.7% | ||
| #1944 | Number of Visible People in a Queue ArrayStackMonotonic Stack | Hard | 77% | 73.3% | ||
| #1438 | Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit ArrayQueueSliding WindowHeap (Priority Queue)Ordered SetMonotonic Queue | Medium | 100% | 57.8% | ||
| #496 | Next Greater Element I ArrayHash TableStackMonotonic Stack | Easy | 82% | 76.5% | ||
| #85 | Maximal Rectangle ArrayDynamic ProgrammingStackMatrixMonotonic Stack | Hard | 64% | 0.6% | ||
| #907 | Sum of Subarray Minimums ArrayDynamic ProgrammingStackMonotonic Stack | Medium | 88% | 38.8% | ||
| #316 | Remove Duplicate Letters StringStackGreedyMonotonic Stack | Medium | 100% | 0.5% | ||
| #853 | Car Fleet ArrayStackSortingMonotonic Stack | Medium | 100% | 55.4% | ||
| #918 | Maximum Sum Circular Subarray ArrayDivide and ConquerDynamic ProgrammingQueueMonotonic Queue | Medium | 90% | 50.7% | ||
| #2444 | Count Subarrays With Fixed Bounds ArrayQueueSliding WindowMonotonic Queue | Hard | 88% | 69.2% | ||
| #556 | Next Greater Element III MathTwo PointersString | Medium | 65% | 35.4% | ||
| #581 | Shortest Unsorted Continuous Subarray ArrayTwo PointersStackGreedySortingMonotonic Stack | Medium | 100% | 38.4% | ||
| #1081 | Smallest Subsequence of Distinct Characters StringStackGreedyMonotonic Stack | Medium | 100% | 63.7% | ||
| #1574 | Shortest Subarray to be Removed to Make Array Sorted ArrayTwo PointersBinary SearchStackMonotonic Stack | Medium | 97% | 51.4% | ||
| #2104 | Sum of Subarray Ranges ArrayStackMonotonic Stack | Medium | 88% | 61.5% | ||
| #962 | Maximum Width Ramp ArrayTwo PointersStackMonotonic Stack | Medium | 88% | 55.9% | ||
| #862 | Shortest Subarray with Sum at Least K ArrayBinary SearchQueueSliding WindowHeap (Priority Queue)Prefix SumMonotonic Queue | Hard | 100% | 32.9% | ||
| #1526 | Minimum Number of Increments on Subarrays to Form a Target Array ArrayDynamic ProgrammingStackGreedyMonotonic Stack | Hard | 67% | 78.2% | ||
| #321 | Create Maximum Number ArrayTwo PointersStackGreedyMonotonic Stack | Hard | 64% | 0.4% | ||
| #456 | 132 Pattern ArrayBinary SearchStackMonotonic StackOrdered Set | Medium | 54% | 34.9% | ||
| #901 | Online Stock Span StackDesignMonotonic StackData Stream | Medium | 50% | 69.4% | ||
| #1475 | Final Prices With a Special Discount in a Shop ArrayStackMonotonic Stack | Easy | 100% | 84.2% | ||
| #1696 | Jump Game VI ArrayDynamic ProgrammingQueueHeap (Priority Queue)Monotonic Queue | Medium | 100% | 46.5% | ||
| #769 | Max Chunks To Make Sorted ArrayStackGreedySortingMonotonic Stack | Medium | 77% | 64.2% | ||
| #1008 | Construct Binary Search Tree from Preorder Traversal ArrayStackTreeBinary Search TreeMonotonic StackBinary Tree | Medium | 38% | 84.4% | ||
| #255 | Verify Preorder Sequence in Binary Search Tree ArrayStackTreeBinary Search TreeRecursionMonotonic StackBinary Tree | Medium | 100% | 51.8% | ||
| #1762 | Buildings With an Ocean View ArrayStackMonotonic Stack | Medium | 88% | 80.9% | ||
| #2071 | Maximum Number of Tasks You Can Assign ArrayTwo PointersBinary SearchGreedyQueueSortingMonotonic Queue | Hard | 88% | 50.0% | ||
| #2940 | Find Building Where Alice and Bob Can Meet ArrayBinary SearchStackBinary Indexed TreeSegment TreeHeap (Priority Queue)Monotonic Stack | Hard | 75% | 52.4% | ||
| #2762 | Continuous Subarrays ArrayQueueSliding WindowHeap (Priority Queue)Ordered SetMonotonic Queue | Medium | 38% | 58.0% | ||
| #768 | Max Chunks To Make Sorted II ArrayStackGreedySortingMonotonic Stack | Hard | 28% | 55.0% | ||
| #2334 | Subarray With Elements Greater Than Varying Threshold ArrayStackUnion-FindMonotonic Stack | Hard | 100% | 45.8% | ||
| #1130 | Minimum Cost Tree From Leaf Values ArrayDynamic ProgrammingStackGreedyMonotonic StackCartesian Tree | Medium | 88% | 67.9% | ||
| #1856 | Maximum Subarray Min-Product ArrayStackMonotonic StackPrefix SumCartesian Tree | Medium | 50% | 40.6% | ||
| #1019 | Next Greater Node In Linked List ArrayLinked ListStackMonotonic Stack | Medium | 38% | 64.5% | ||
| #654 | Maximum Binary Tree ArrayDivide and ConquerStackTreeMonotonic StackBinary TreeCartesian Tree | Medium | 27% | 86.4% | ||
| #1504 | Count Submatrices With All Ones ArrayDynamic ProgrammingStackMatrixMonotonic Stack | Medium | 26% | 71.0% | ||
| #2487 | Remove Nodes From Linked List Linked ListStackRecursionMonotonic Stack | Medium | 25% | 75.0% | ||
| #3542 | Minimum Operations to Convert All Elements to Zero ArrayHash TableStackGreedyMonotonic Stack | Medium | 18% | 53.1% | ||
| #3578 | Count Partitions With Max-Min Difference at Most K ArrayDynamic ProgrammingQueueSliding WindowPrefix SumMonotonic Queue | Medium | 13% | 58.5% | ||
| #2617 | Minimum Number of Visited Cells in a Grid ArrayDynamic ProgrammingStackBreadth-First SearchUnion-FindHeap (Priority Queue)MatrixMonotonic Stack | Hard | 100% | 24.0% | ||
| #3878 | Count Good Subarrays ArrayStackBit ManipulationMonotonic Stack | Hard | 89% | 25.5% | ||
| #1124 | Longest Well-Performing Interval ArrayHash TableStackMonotonic StackPrefix Sum | Medium | 75% | 37.9% | ||
| #975 | Odd Even Jump ArrayDynamic ProgrammingStackSortingMonotonic StackOrdered Set | Hard | 65% | 41.3% | ||
| #3229 | Minimum Operations to Make Array Equal to Target ArrayDynamic ProgrammingStackGreedyMonotonic Stack | Hard | 29% | 41.8% | ||
| #1966 | Binary Searchable Numbers in an Unsorted Array ArrayBinary SearchStackMonotonic Stack | Medium | 28% | 63.8% | ||
| #1776 | Car Fleet II ArrayMathStackHeap (Priority Queue)Monotonic Stack | Hard | 25% | 58.2% | ||
| #3816 | Lexicographically Smallest String After Deleting Duplicate Characters Hash TableStringStackGreedyMonotonic Stack | Hard | 100% | 20.7% | ||
| #1425 | Constrained Subsequence Sum ArrayDynamic ProgrammingQueueSliding WindowHeap (Priority Queue)Monotonic Queue | Hard | 100% | 56.5% | ||
| #2398 | Maximum Number of Robots Within Budget ArrayBinary SearchQueueSliding WindowHeap (Priority Queue)Prefix SumMonotonic Queue | Hard | 67% | 38.8% | ||
| #3676 | Count Bowl Subarrays ArrayStackMonotonic Stack | Medium | 38% | 48.5% | ||
| #2345 | Finding the Number of Visible Mountains ArrayStackSortingMonotonic Stack | Medium | 28% | 37.5% | ||
| #2407 | Longest Increasing Subsequence II ArrayDivide and ConquerDynamic ProgrammingBinary Indexed TreeSegment TreeQueueMonotonic Queue | Hard | 25% | 0.3% | ||
| #1673 | Find the Most Competitive Subsequence ArrayStackGreedyMonotonic Stack | Medium | 25% | 53.2% | ||
| #3113 | Find the Number of Subarrays Where Boundary Elements Are Maximum ArrayBinary SearchStackMonotonic Stack | Hard | 25% | 33.7% | ||
| #1793 | Maximum Score of a Good Subarray ArrayTwo PointersBinary SearchStackMonotonic StackCartesian Tree | Hard | 25% | 64.2% | ||
| #3420 | Count Non-Decreasing Subarrays After K Operations ArrayStackSegment TreeQueueSliding WindowMonotonic StackMonotonic Queue | Hard | 25% | 24.9% | ||
| #2818 | Apply Operations to Maximize Score ArrayMathStackGreedySortingMonotonic StackNumber Theory | Hard | 13% | 53.6% | ||
| #1687 | Delivering Boxes from Storage to Ports ArrayDynamic ProgrammingSegment TreeQueueHeap (Priority Queue)Prefix SumMonotonic Queue | Hard | 100% | 39.9% | ||
| #3205 | Maximum Array Hopping Score I ArrayDynamic ProgrammingStackGreedyMonotonic Stack | Medium | 100% | 77.1% | ||
| #3221 | Maximum Array Hopping Score II ArrayStackGreedyMonotonic Stack | Medium | 100% | 59.8% | ||
| #1063 | Number of Valid Subarrays ArrayStackMonotonic Stack | Hard | 100% | 80.1% | ||
| #2030 | Smallest K-Length Subsequence With Occurrences of a Letter StringStackGreedyMonotonic Stack | Hard | 100% | 40.0% | ||
| #2866 | Beautiful Towers II ArrayStackMonotonic Stack | Medium | 63% | 36.8% | ||
| #2865 | Beautiful Towers I ArrayStackMonotonic Stack | Medium | 63% | 44.7% | ||
| #2282 | Number of People That Can Be Seen in a Grid ArrayStackMatrixMonotonic Stack | Medium | 50% | 47.4% | ||
| #2281 | Sum of Total Strength of Wizards ArrayStackMonotonic StackPrefix Sum | Hard | 40% | 29.6% | ||
| #2355 | Maximum Number of Books You Can Take ArrayDynamic ProgrammingStackMonotonic Stack | Hard | 38% | 39.5% | ||
| #2289 | Steps to Make Array Non-decreasing ArrayLinked ListDynamic ProgrammingStackMonotonic StackSimulation | Medium | 25% | 25.0% | ||
| #2297 | Jump Game VIII ArrayDynamic ProgrammingStackGraph TheoryMonotonic StackShortest Path | Medium | 25% | 45.9% | ||
| #1950 | Maximum of Minimum Values in All Subarrays ArrayStackMonotonic StackCartesian Tree | Medium | 25% | 48.2% | ||
| #2832 | Maximal Range That Each Element Is Maximum in It ArrayStackMonotonic Stack | Medium | 25% | 75.3% | ||
| #1996 | The Number of Weak Characters in the Game ArrayStackGreedySortingMonotonic Stack | Medium | 25% | 44.6% | ||
| #1499 | Max Value of Equation ArrayQueueSliding WindowHeap (Priority Queue)Monotonic Queue | Hard | 25% | 45.1% | ||
| #683 | K Empty Slots ArrayBinary Indexed TreeSegment TreeQueueSliding WindowHeap (Priority Queue)Ordered SetMonotonic Queue | Hard | 25% | 38.0% | ||
| #2863 | Maximum Length of Semi-Decreasing Subarrays ArrayStackSortingMonotonic Stack | Medium | 25% | 70.0% | ||
| #3638 | Maximum Balanced Shipments ArrayDynamic ProgrammingStackGreedyMonotonic Stack | Medium | 16% | 61.5% | ||
| #2454 | Next Greater Element IV ArrayBinary SearchStackSortingHeap (Priority Queue)Monotonic Stack | Hard | 13% | 42.3% | ||
| #3523 | Make Array Non-decreasing ArrayStackGreedyMonotonic Stack | Medium | 13% | 57.5% | ||
| #3589 | Count Prime-Gap Balanced Subarrays ArrayMathQueueSliding WindowNumber TheoryMonotonic Queue | Medium | 13% | 23.7% |
Showing 86 of 86 problems in Monotonic Stack & QueueFiltered: All Companies