Nearest greater/smaller elements and range extremums in linear time
85 problems·2 Easy·50 Medium·33 Hard
Pattern Study Guide & Cheat Sheet· O(n) amortized (each index pushed and popped at most once) · O(n) for stack and result array
▼
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
What is the Monotonic Stack & Queue pattern in coding interviews?
Nearest greater/smaller elements and range extremums in linear time It is categorized under Data Structures and features 85 curated interview problems across Easy (2), Medium (50), and Hard (33) difficulties.
Which tech companies frequently test Monotonic Stack & Queue?
How do I master the Monotonic Stack & Queue pattern?
Start by studying the algorithmic strategy and template code, then practice Easy and Medium problems before attempting Hard problems under timed conditions.