Greedy Algorithms & Monotonic Stack — Complete Guide
Advertisement
Greedy Algorithms
A greedy algorithm makes the locally optimal choice at each step, hoping it leads to a global optimum. Works when the problem has the greedy choice property: a global optimal solution can be built from locally optimal choices.
The 5 Core Greedy Patterns
Pattern 1 — Interval Scheduling (Sort by End Time)
Maximize number of non-overlapping intervals by greedily picking the earliest-ending activity.
intervals.sort(key=lambda x: x[1]) # sort by end
count = 0; prev_end = -inf
for start, end in intervals:
if start >= prev_end:
count += 1; prev_end = end
Pattern 2 — Activity Selection / Job Scheduling
Schedule jobs greedily to maximize profit. Sort by deadline or profit-per-unit.
Pattern 3 — Huffman / Greedy Coding
Minimum total cost to connect cables: always connect two cheapest. Priority queue (min-heap).
Pattern 4 — Two-Pointer Greedy
Assign people to tasks optimally. Sort both arrays, match greedily.
Pattern 5 — Candy / Fair Distribution
Local constraints from both sides. Two-pass: left-to-right then right-to-left.
Monotonic Stack
A monotonic stack maintains elements in increasing or decreasing order. Elements are popped when a better candidate arrives.
Pattern 6 — Next Greater Element
stack = []
for i in range(n):
while stack and nums[stack[-1]] < nums[i]:
idx = stack.pop()
result[idx] = nums[i] # nums[i] is NGE for idx
stack.append(i)
Pattern 7 — Largest Rectangle in Histogram
stack = [-1] # sentinel
for i, h in enumerate(heights):
while stack[-1] != -1 and heights[stack[-1]] >= h:
height = heights[stack.pop()]
width = i - stack[-1] - 1
area = height * width; max_area = max(max_area, area)
stack.append(i)
# process remaining
while stack[-1] != -1:
height = heights[stack.pop()]
width = len(heights) - stack[-1] - 1
max_area = max(max_area, height * width)
Complexity Reference
| Pattern | Time | Space |
|---|---|---|
| Interval Sort | O(n log n) | O(1) |
| Next Greater Element | O(n) | O(n) |
| Histogram Area | O(n) | O(n) |
| Trapping Rain Water | O(n) | O(1) two-pointer |
Problem Index
| # | Problem | Pattern | Difficulty |
|---|---|---|---|
| 01 | Assign Cookies | Two-pointer greedy | Easy |
| 02 | Non-overlapping Intervals | Interval scheduling | Medium |
| 03 | Minimum Number of Arrows | Interval piercing | Medium |
| 04 | Meeting Rooms II | Greedy + heap | Medium |
| 05 | Task Scheduler (revisit) | Greedy formula | Medium |
| 06 | Jump Game (revisit) | Greedy reach | Medium |
| 07 | Gas Station | Greedy circular | Medium |
| 08 | Candy | Two-pass greedy | Hard |
| 09 | Next Greater Element I | Monotonic stack | Easy |
| 10 | Next Greater Element II (circular) | Monotonic stack | Medium |
| 11 | Daily Temperatures | Monotonic stack | Medium |
| 12 | Largest Rectangle in Histogram | Monotonic stack | Hard |
| 13 | Maximal Rectangle | Histogram per row | Hard |
| 14 | Trapping Rain Water | Two-pointer / stack | Hard |
| 15 | Remove Duplicate Letters | Monotonic stack | Medium |
| 16 | Remove K Digits | Monotonic stack | Medium |
| 17 | Sum of Subarray Minimums | Monotonic stack | Medium |
| 18 | 132 Pattern | Monotonic stack | Medium |
| 19 | Largest Rectangle in BST (Beautiful Arrangement) | Greedy | Medium |
| 20 | Maximum Width Ramp | Monotonic stack | Medium |
| 21 | Minimum Cost to Connect Sticks | Min-heap greedy | Medium |
| 22 | Greedy + Monotonic Stack Master Recap | Cheatsheet | — |
Advertisement