Greedy & Monotonic Stack — Master Recap & Cheatsheet

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

Greedy & Monotonic Stack Master Cheatsheet


Greedy Patterns

PatternKey InsightSort/Order
Interval SchedulingKeep earliest-endingSort by end time
Interval PiercingSame as aboveSort by end time
Candy Two-PassLeft then right constraintsTwo O(n) passes
Gas StationIf total ok, reset at negativeLinear scan
Partition LabelsExtend to last occurrenceTrack last occurrence
Queue ReconstructionInsert taller firstSort by height desc
Assign Tasks GreedyMatch smallest sufficientSort both

Monotonic Stack Patterns

PatternStack TypeTrigger Pop
Next GreaterDecreasingcurrent > stack top
Next SmallerIncreasingcurrent < stack top
Histogram AreaIncreasingcurrent < stack top
Trapping RainDecreasing (by index)current > stack top
Remove K DigitsIncreasingcurrent < stack top AND k > 0
Sum Subarray MinIncreasingcurrent < stack top (left), right scan for right

Monotonic Stack Template

stack = []  # or [-1] for sentinel
for i, val in enumerate(arr):
    # For DECREASING stack (Next Greater Element):
    while stack and arr[stack[-1]] < val:
        idx = stack.pop()
        result[idx] = val  # val is NGE for idx
    stack.append(i)

Histogram Template

heights.append(0)  # sentinel
stack = [-1]
for i, h in enumerate(heights):
    while stack[-1] != -1 and heights[stack[-1]] >= h:
        height = heights[stack.pop()]
        width = i - stack[-1] - 1
        max_area = max(max_area, height * width)
    stack.append(i)

Problem Index

Greedy: Assign Cookies (01), Non-overlap Intervals (02), Arrows (03), Gas Station (04), Candy (05), Partition Labels (18), Queue Reconstruction (19), Min Cost Sticks (17), Max Chunks (21)

Monotonic Stack: NGE I (06), Daily Temps (07), Largest Rect Histogram (08), Trapping Rain (09), Remove Duplicates (10), Remove K Digits (11), Sum Subarray Min (12), Max Width Ramp (13), 132 Pattern (14), Maximal Rectangle (15), NGE II Circular (16)

Monotonic Deque: Jump Game VI (20)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro