Day 31: Greedy Algorithms | Exchange Arguments & Interval Scheduling Internals
Exchange argument proofs, activity selection sorting keys, 0/1 vs fractional counterexamples, and O(N log N) internals.
Why does grabbing the locally best choice right in front of you yield the exact global optimum for scheduling meetings and compressing files—yet fail catastrophically when making change for odd coin denominations?
1. In 30 Seconds
A Greedy Algorithm builds a solution step by step, always locking in the single choice that looks best right at that exact moment without ever looking back or reconsidering past decisions. Unlike Dynamic Programming, which explores all subproblems and weighs future trade-offs, a greedy strategy commits irrevocably to a local optimum. When a problem satisfies the Greedy Choice Property and Optimal Substructure—provable via an Exchange Argument—greedy algorithms deliver optimal solutions in $O(N \log N)$ or $O(N)$ time with $O(1)$ auxiliary memory.
2. The Real-World Analogy: Packing a Carry-On Bag with Gold Dust vs. Laptops
Imagine you have 60 seconds to fill a 10 kg backpack inside a vault containing open sacks of spices and gold dust.
- If you can scoop any fraction of a sack (Fractional Knapsack), the greedy rule is obvious and 100% optimal: sort items by value per kilogram and scoop as much of the highest-ratio item as fits before moving to the next.
- Now swap those open sacks for sealed, indivisible electronics (0/1 Knapsack): a 6 kg gold bar worth $600 ($100/kg) and two 5 kg laptops worth $450 each ($90/kg).
- A greedy thief grabs the $100/kg gold bar first, leaving 4 kg of empty air and walking out with $600—missing the optimal $900 pair of laptops because indivisible items leave wasted slack!
3. Picture This
Diagram 1: Activity Selection — Why Sorting by Earliest Finish Time Wins
Meeting Requests on a Timeline (0 to 10):
Meeting A: [0 ----------------------- 9] (Starts earliest, blocks everything!)
Meeting B: [1 -- 3] (Finishes earliest at t=3!)
Meeting C: [3 ---- 6] (Finishes at t=6!)
Meeting D: [5 ------ 8]
Meeting E: [6 ------ 9] (Finishes at t=9!)
Greedy Rule: Sort by END TIME ascending!
1. Pick Meeting B [1, 3] -> Room frees up at t = 3 (Maximizes remaining room time!)
2. Skip A (starts 0 < 3). Pick Meeting C [3, 6] -> Room frees up at t = 6.
3. Skip D (starts 5 < 6). Pick Meeting E [6, 9] -> Room frees up at t = 9.
Result: 3 meetings scheduled (Optimal!), whereas sorting by Start Time or Duration fails!
Walkthrough: Sorting by earliest start time picks Meeting A [0, 9] and traps you with just 1 meeting. Sorting by earliest finish time leaves the maximum possible unused timeline after every single choice.
Diagram 2: The Exchange Argument Proof (Red-Coder Proof Technique)
Suppose Optimal Schedule O starts with meeting o_1, and Greedy picks g_1:
Timeline: 0 -----[ g_1 ]-----> end(g_1)
0 -------[ o_1 ]-----> end(o_1)
Because Greedy picked the earliest finish time: end(g_1) <= end(o_1)
Therefore, swapping o_1 out for g_1 NEVER overlaps with o_2, o_3, ...!
New Schedule O' = [g_1, o_2, o_3, ...] has the EXACT SAME count as O!
By induction across all steps, Greedy is guaranteed globally optimal.
Walkthrough: Whenever you suspect a problem is greedy, test whether replacing the first choice of an optimal solution with your greedy choice preserves feasibility without hurting the objective.
4. How It Actually Works (First Principles & Invariants)
- Identify the Sorting Key (Monotonic Ordering): Almost 80% of greedy problems begin by sorting input intervals or items by a single metric—such as
end_time,start_time,weight / value, ordeadline - duration. - The Remaining-Resource Invariant: At step $k$, after making $k$ greedy choices, the remaining capacity or timeline $[t_k, \infty)$ is strictly a superset of the remaining resource left by any competing strategy.
- Counterexample Stress-Testing (Before Writing Code): Never trust a greedy hunch blindly! Spend 60 seconds trying to break your rule with a 3-item adversarial test case (e.g., coins
[1, 3, 4]for target6: greedy picks4 + 1 + 1= 3 coins, while optimal is3 + 3= 2 coins). - CPU Cache & Sorting Efficiency: Python's Timsort sorts tuples/arrays in $O(N \log N)$ with near-linear performance on partially ordered runs, followed by a single cache-friendly linear scan ($O(N)$) requiring zero DP lookup tables.
5. Show Me The Code
Here is a clean, scratch-built Python implementation covering both Maximum Non-Overlapping Intervals (Activity Selection) and Fractional Knapsack.
# Day 31: Greedy Algorithms — Activity Selection & Fractional Knapsack in Python
def max_non_overlapping_meetings(intervals):
"""
Given a list of [start, end] intervals, returns the maximum number of
non-overlapping meetings you can attend.
Time Complexity: O(N log N) due to sorting by end time.
Space Complexity: O(1) auxiliary space (sorting in-place).
"""
if not intervals:
return 0
# Greedy Choice: Sort strictly by finish time ascending
intervals.sort(key=lambda interval: interval[1])
count = 1
last_end = intervals[0][1]
for start, end in intervals[1:]:
# If the next meeting starts at or after the previous one ends, take it!
if start >= last_end:
count += 1
last_end = end
return count
def fractional_knapsack(capacity, items):
"""
`items` is a list of (value, weight) tuples.
Fractions of items may be taken. Maximizes total value.
Time Complexity: O(N log N)
Space Complexity: O(N) for sorted copy
"""
# Sort descending by value-to-weight density ratio
ranked = sorted(items, key=lambda item: item[0] / item[1], reverse=True)
total_value = 0.0
remaining = capacity
for value, weight in ranked:
if remaining == 0:
break
if weight <= remaining:
total_value += value
remaining -= weight
else:
# Take exact fraction that fills remaining bag capacity
fraction = remaining / weight
total_value += value * fraction
remaining = 0
return total_value
if __name__ == "__main__":
meetings = [[0, 9], [1, 3], [3, 6], [5, 8], [6, 9]]
print("Max meetings attended:", max_non_overlapping_meetings(meetings)) # 3
loot = [(60, 10), (100, 20), (120, 30)]
print("Max knapsack value: ", fractional_knapsack(50, loot)) # 240.0
6. Dry Run
Tracing max_non_overlapping_meetings([[0, 9], [1, 3], [3, 6], [5, 8], [6, 9]]):
| Step | Sorted Interval | Condition start >= last_end | Action | last_end | count |
|---|---|---|---|---|---|
| 1 | [1, 3] | Initial first choice | Select [1, 3] | 3 | 1 |
| 2 | [3, 6] | 3 >= 3 (True) | Select [3, 6] | 6 | 2 |
| 3 | [5, 8] | 5 >= 6 (False) | Skip overlapping | 6 | 2 |
| 4 | [0, 9] | 0 >= 6 (False) | Skip overlapping | 6 | 2 |
| 5 | [6, 9] | 6 >= 6 (True) | Select [6, 9] | 9 | 3 |
7. Speed & Memory
Sorting $N$ records dominates execution time at $O(N \log N)$, while the greedy decision scan touches every item once in $O(N)$ time and $O(1)$ extra space.
| Metric | Complexity | Reason |
|---|---|---|
| Time (Best / Avg / Worst) | $O(N \log N)$ | Dominated by initial sort; single linear pass follows. |
| Space (Auxiliary) | $O(1)$ to $O(N)$ | Zero recursion stack or 2D DP tables needed. |
8. Where You'll See It In Real Life
- Huffman Data Compression (ZIP, JPEG, MP3): Repeatedly merging the two lowest-frequency characters into a binary tree produces provably optimal prefix-free binary codes.
- Operating System CPU Job Scheduling (Shortest Job First): Minimizing average waiting time across batch processes by executing shortest burst times first.
- Network Routing & Spanning Trees (Dijkstra, Prim, Kruskal): Greedily locking in minimum-weight edges or shortest frontiers at each step.
9. Traps To Avoid
- Trap 1: Applying Greedy to 0/1 Knapsack or arbitrary Coin Change denominations.
Fix: Whenever choices are indivisible and future combinations interact, test a small counterexample—if greedy breaks, switch to Dynamic Programming. - Trap 2: Sorting intervals by
start_timeinstead ofend_timewhen maximizing non-overlapping count.
Fix: Sort byend_timeto maximize remaining intervals, and bystart_timewhen merging overlapping intervals. - Trap 3: Dividing integers carelessly or missing floating-point precision in ratio comparisons.
Fix: In languages with integer division, compare ratios using cross-multiplication (v1 * w2 > v2 * w1) to avoid precision bugs.
10. Practice
- Easy (Assign Cookies): Given children's greed factors and cookie sizes, maximize satisfied children where each child gets at most one cookie of size $\ge \text{greed}[i]$. Hint: Sort both arrays ascending and match smallest valid cookies with two pointers.
- Medium (Jump Game): Given an array where
nums[i]is your maximum jump length from index $i$, determine if you can reach the final index. Hint: Track the single greedy variablefarthest_reachablein one $O(N)$ pass. - Hard (Minimum Number of Platforms / Meeting Rooms II): Given arrival and departure times of $N$ trains, find the minimum platforms required so no train waits. Hint: Sort arrivals and departures separately and sweep a two-pointer timeline counter!
11. TL;DR
- Greedy Algorithms make the locally optimal choice at every step without backtracking, running in $O(N \log N)$ time and $O(1)$ extra space.
- Verify correctness with an Exchange Argument or a 3-item counterexample before coding.
- For interval maximization, always sort by earliest finish time.
12. References Consulted
- GeeksforGeeks — Greedy Algorithms Tutorial — referenced for verification — all content above is original.
- Programiz — Greedy Algorithm Basics — referenced for verification — all content above is original.
13. Covered Log Update
Already covered: Big-O notation, Arrays, Two Pointers, Strings, Sliding Window, Prefix Sums, Recursion basics, Singly Linked List, Doubly Linked List, Stack, Queue, Deque, Fast & Slow pointers, Binary Search, Bubble/Selection/Insertion Sort, Merge Sort, Quick Sort, Counting & Bucket Sort, Hashing & Hash Maps, Binary Tree, Tree Traversals (DFS/BFS), Binary Search Tree, Heap & Priority Queue, Trie, Graph representations, BFS, Depth-First Search (DFS), Topological Sort, Union-Find, Dijkstra's Shortest Path, Greedy algorithms.