Greedy Algorithms: Making Locally Optimal Choices
Learn when greedy algorithms are correct, prove a choice with an exchange argument, and compare activity selection, Huffman coding, and knapsack.
Greedy algorithms make locally best choices, but correctness depends on the problem and needs a proof. This guide uses activity selection to show an exchange argument, contrasts fractional and 0/1 knapsack, and explains why equal-frequency Huffman merges can produce different valid codes. Runtime also depends on the chosen data structures: activity selection takes O(n log n) when sorting is needed and O(n) when activities arrive sorted by finish time.
Greedy Algorithms: Making Locally Optimal Choices
Introduction
Greedy algorithms are the simplest algorithmic paradigm: at each step, make the choice that looks best right now, never reconsidering past decisions. The challenge is proving this local optimality leads to global optimality.
For a common proof approach, show that some optimal solution contains the greedy choice at each step, then reduce the remaining problem and use induction. Runtime is separate: for example, sorting activities by finish time takes O(n log n), followed by an O(n) scan; if they are already sorted, the scan is O(n). Other greedy algorithms have different costs.
Activity Selection Problem
The classic greedy problem: select the maximum number of non-overlapping activities:
def activity_selection(activities):
"""
Select maximum set of non-overlapping activities.
Args:
activities: List of (start, end) tuples
Returns:
List of selected activity indices
"""
if not activities:
return []
# Sort by finish time (key greedy choice!)
sorted_activities = sorted(enumerate(activities), key=lambda x: x[1][1])
selected = [sorted_activities[0][0]]
last_end = sorted_activities[0][1][1]
for idx, (start, end) in sorted_activities[1:]:
if start >= last_end: # Non-overlapping with last selected
selected.append(idx)
last_end = end
return selected
Why earliest finish is safe
Let g be the activity that finishes first, and let an optimal schedule begin with activity a. Since g finishes no later than a, replacing a with g leaves every later activity in that schedule feasible. The replacement keeps the number of scheduled activities unchanged, so there is an optimal schedule that starts with g. After choosing g, discard activities that overlap it and solve the same problem on the remainder. Repeating this argument proves the algorithm returns a maximum-size schedule.
With n activities, sorting plus the scan takes O(n log n); if the activities are already ordered by finish time, the scan takes O(n).
Huffman Coding
Greedy compression builds an optimal prefix-free code by repeatedly merging two minimum-frequency nodes. If frequencies tie, different merge orders can produce different code assignments with the same optimal weighted path length. The example below does not promise a stable code for ties; add an explicit secondary key if byte-for-byte reproducibility matters.
import heapq
from collections import Counter
class HuffmanNode:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def huffman_coding(text):
"""Build Huffman coding tree and return code mapping."""
if not text:
return {}
# Build initial min-heap of characters
freq = Counter(text)
heap = [HuffmanNode(char, f) for char, f in freq.items()]
heapq.heapify(heap)
# Build tree by merging two minimum frequency nodes
while len(heap) > 1:
left = heapq.heappop(heap)
right = heapq.heappop(heap)
merged = HuffmanNode(None, left.freq + right.freq)
merged.left, merged.right = left, right
heapq.heappush(heap, merged)
root = heap[0]
# Traverse to build codes
codes = {}
def traverse(node, code):
if node.char is not None:
codes[node.char] = code or '0' # Handle single character
else:
traverse(node.left, code + '0')
traverse(node.right, code + '1')
traverse(root, '')
return codes
When Greedy Works
Greedy is correct when:
- The problem has optimal substructure AND the greedy choice doesn’t preclude optimal solutions
- A greedy choice property holds: there’s an optimal solution that makes the greedy choice
- Proof via exchange argument: any optimal solution can be transformed to the greedy solution without worsening the outcome
Common greedy problems:
- Activity selection (sort by finish time)
- Fractional knapsack (sort by value/weight ratio)
- Huffman coding (merge smallest frequencies)
- Minimum spanning tree (Prim’s, Kruskal’s)
- Dijkstra’s shortest path (select minimum distance vertex)
When Greedy Fails
A ratio choice works for fractional knapsack because an item can be split. It does not solve 0/1 knapsack, where each item must be taken whole. For capacity 50, consider items (weight, value) of (10, 60), (20, 100), and (30, 120). Ratio order takes the first two for value 160 and leaves 20 units unused; the last two fit exactly and yield 220. In the fractional version, the ratio order can take the first two plus two-thirds of the third, for value 240.
The counterexample shows why the fractional proof does not transfer to 0/1 choices. For 0/1 knapsack, use an algorithm suited to the required constraints, such as dynamic programming, and account for its dependence on capacity.
Proving Greedy Correctness
def prove_greedy_correct(problem):
"""
Template for proving greedy correctness via exchange argument:
1. Claim: There exists an optimal solution that makes the greedy choice
2. Assume an optimal solution O differs at first greedy choice
3. Exchange: Replace O's choice with the greedy choice
4. Show: The exchange doesn't make the solution worse
5. Repeat for subsequent choices
"""
pass
Common Greedy Patterns
| Pattern | Greedy Choice | Example |
|---|---|---|
| Sort by finish time | Earliest finishing first | Activity selection |
| Sort by ratio | Highest value/weight | Fractional knapsack |
| Priority queue | Smallest/largest available | Dijkstra, Prim’s |
| Two pointers | Move pointer with smaller value | Water container |
Trade-off Analysis
| Aspect | Greedy | Dynamic Programming |
|---|---|---|
| Time | Depends on sorting, scans, and data structures; activity selection is O(n log n) when sorting is needed | Depends on the state space; 0/1 knapsack dynamic programming is O(nW) for n items and integer capacity W |
| Space | Depends on stored choices and data structures | Depends on the state representation; a 0/1 knapsack table can use O(nW), or O(W) with a one-dimensional update |
| Correctness | Problem-specific proof | Always correct if substructure holds |
| Flexibility | Low | High |
| Implementation | Usually simple | Can be complex |
Common Pitfalls / Anti-Patterns
- Assuming a local choice is safe: intuition is not a proof. State the greedy choice and show an exchange or cut argument for the specific problem.
- Confusing fractional and 0/1 knapsack: sorting by value-to-weight ratio is optimal when items can be split. It can fail when each item must be taken whole.
- Ignoring tie behavior: equal keys can produce different valid outputs. Add a stable secondary key when reproducible output matters; first check that the tie-break does not change correctness.
- Quoting one complexity for every greedy algorithm: count the work for the chosen algorithm and data structure, including sorting, heap operations, and scans. The greedy-choice property says nothing by itself about runtime.
- Treating input validation as an algorithmic proof: validate values and constraints at the application boundary, then prove the algorithm optimizes the intended objective.
Greedy Choice vs Exhaustive Search
graph TD
A["Problem input"] --> B{"Problem has greedy-choice property?"}
B -->|Yes| C["Make locally optimal choice"]
C --> D{"Recurse or iterate?"}
D -->|Iterate| E["Make next greedy choice"]
E --> F{"All choices made?"}
F -->|No| E
F -->|Yes| G["Return solution Globally optimal"]
B -->|No| H["Use exhaustive search or dynamic programming"]
H --> I["Explore all possibilities Find optimal solution"]
Quick Recap Checklist
- Check if problem has greedy-choice property
- Prove via exchange argument or cut-and-paste
- Sort appropriately (usually by some key)
- Iterate making locally optimal choices
- Handle edge cases (empty input, single element)
- Verify no counter-examples exist
Production Failure Scenarios
-
Greedy choice not being globally optimal: This is the most common greedy failure—applying greedy to a problem where the local optimum doesn’t guarantee a global optimum. The 0/1 knapsack problem is the classic example: greedy by value/weight ratio fails because taking a high-ratio item can block you from multiple lower-ratio items. Always prove correctness via exchange argument before implementing, and log when greedy produces suboptimal results in test cases.
-
Lack of optimal substructure: Even when the greedy choice property holds locally, the problem might not have optimal substructure—the optimal solution doesn’t consist of optimal solutions to subproblems. Without optimal substructure, greedy cannot work even if individual choices seem correct.
-
Floating-point comparisons causing incorrect ordering: When sorting by ratios (like value/weight in fractional knapsack), floating-point precision can cause items that should be equal to sort in unpredictable orders. This leads to non-deterministic behavior. Use integer arithmetic where possible (e.g., compare
a.weight * b.valuevsb.weight * a.valueinstead of dividing). -
Integer overflow in priority calculations: For Huffman coding with very large frequencies or Dijkstra with large weights, accumulating values in priority queues can overflow. Use bounded integer types or detect overflow before it happens.
Interview Questions
The standard method is exchange argument: Show that any optimal solution can be transformed into the greedy solution without worsening its value. You prove that at each step, the greedy choice is safe—replacing whatever the optimal solution does at that step with the greedy choice doesn't break optimality. Alternatively, prove via induction: the greedy solution is optimal for the first k choices implies it's optimal for choice k+1.
Both are greedy, but they grow differently. Kruskal's looks at all edges globally, sorts them, and adds the cheapest edge that doesn't create a cycle (using union-find). Prim's grows one tree from a start vertex, always adding the cheapest edge connecting the tree to an outside vertex (using a priority queue). Kruskal's is often simpler; Prim's can be faster for dense graphs.
In fractional knapsack, you can take any fraction of an item, so taking the item with best value/weight ratio is always safe. But in 0/1 knapsack, you must take whole items. Taking an item with high ratio might block you from taking multiple smaller items that together exceed its value. The greedy choice creates a local optimum that isn't global. This requires DP to solve correctly.
Choose greedy when you can prove the choice is safe and its runtime and memory fit the constraints. Compare actual costs for the specific algorithms: sorting plus a scan may be O(n log n), while a 0/1 knapsack DP is O(nW). Use dynamic programming when the problem has suitable optimal substructure and overlapping subproblems but no valid greedy-choice proof. Do not treat a few passing examples as evidence that greedy is correct.
Expected answer points:
- Dijkstra finds shortest paths from a source vertex to all other vertices in a weighted graph with non-negative edge weights
- It's greedy because it always selects the unvisited vertex with smallest known distance, locks in that distance permanently, and never revisits it
- Uses a priority queue (min-heap) to efficiently find the minimum-distance vertex
- Time complexity: O((V+E) log V) with binary heap implementation
- Fails with negative edge weights—use Bellman-Ford instead
Expected answer points:
- Greedy-choice property: A globally optimal solution can be built by making locally optimal choices at each step—there's always an optimal solution that contains the greedy choice
- Optimal substructure: An optimal solution to the problem contains within it optimal solutions to subproblems
- Both properties must hold for greedy to work; optimal substructure alone is necessary but not sufficient (DP also needs it)
- Example: In activity selection, choosing the earliest-finishing activity leaves a subproblem (remaining activities) that is itself an activity selection problem
Expected answer points:
- Builds an optimal prefix-free binary tree for character compression
- Greedy step: repeatedly merge the two nodes with smallest frequency using a min-heap
- Repeatedly merging the two smallest frequencies preserves an optimal weighted path length
- Proof uses exchange argument: any optimal tree can be transformed to one where the two least-frequent characters are siblings at the bottom
- Results in variable-length encoding—frequent characters get short codes, rare characters get longer codes
Expected answer points:
- Given items with weights and values, maximize value in a knapsack with capacity W—you can take fractions of items
- Greedy solution: sort items by value/weight ratio descending, take items whole until capacity nearly reached, then take fraction of last item
- Correct because taking more of a higher-ratio item always improves the solution—no blocking effect since fractions are allowed
- Time complexity: O(n log n) for sorting
- Contrast with 0/1 knapsack where greedy fails
Expected answer points:
- Activity selection finds maximum number of non-overlapping intervals
- Sort activities by finish time: O(n log n)
- Single pass to select activities: O(n)
- Total: O(n log n)
- Can be implemented in O(n) if already sorted by finish time
Expected answer points:
- For unit-time jobs with integer deadlines and profits, choose a feasible schedule with maximum total profit
- Sort jobs by profit descending (greedy by highest value first)
- For each job, place it in the latest available time slot before its deadline using a union-find or slot array
- Proof: taking highest profit job that fits doesn't block more total profit since lower-profit jobs fill earlier slots
- With a slot array and backward scan, runtime is O(n log n + nD), where D is the largest relevant deadline; a disjoint-set slot structure reduces repeated search overhead
Expected answer points:
- Given height array representing container walls, find max water area between two walls
- Greedy: two pointers at ends, move the pointer with smaller height inward
- Why it works: area is limited by shorter wall; moving the shorter wall might find a taller one that increases area
- Proof by contradiction: any optimal solution can be transformed to one using the two-pointer approach
- Time complexity: O(n) with two pointers, much better than O(n²) brute force
Expected answer points:
- Priority queues (min-heaps or max-heaps) efficiently support the "select best available" operation central to greedy
- Used in Dijkstra's, Prim's MST, Huffman coding—allows O(log n) selection of minimum/maximum
- Alternatives: sorting (O(n log n) preprocessing then O(1) selection), arrays for small inputs
- Binary heap provides balance of efficiency and simplicity; Fibonacci heap gives theoretical improvement for Dijkstra
- Key tradeoff: lazy deletion (mark invalid, remove when popped) vs eager deletion (update on change)
Expected answer points:
- Ties can lead to multiple valid greedy solutions—consistency matters for determinism
- When sorting by key (e.g., finish time), add secondary sort key (e.g., start time or ID) for stability
- In priority queues, define consistent tie-breaking in comparator
- A tie-breaker can make output reproducible; it does not replace validation or authorization in resource-allocation systems
- Example: activity selection with same finish time—pick the one with earliest start time or smallest index
Expected answer points:
- Subtle edge cases: the greedy-choice property may hold for small cases but fail at scale
- Hidden dependencies: greedy choice might affect future choices in non-obvious ways
- Counter-example discovery: try adversarial inputs, especially ones where items have equal values
- Proof gaps: lack of formal proof means edge cases may invalidate the approach
- Recommendation: implement both greedy and DP, compare on random test cases before deployment
Expected answer points:
- Greedy: Make local choice, reduce to subproblem, never revisit
- Divide-and-conquer: Split problem, solve subproblems independently, combine results
- Greedy is top-down with irreversible choices; divide-and-conquer often has recomputation
- Greedy examples: activity selection, Huffman coding, Dijkstra
- Divide-and-conquer examples: merge sort, closest pair of points, Strassen's matrix multiplication
- Some problems fit both paradigms but need different insights
Expected answer points:
- A matroid is an independence system satisfying hereditary and exchange properties
- Greedy optimally solves any problem where feasible set forms a matroid and objective is additive
- Examples: spanning trees (graphic matroids), linearly independent vectors (linear matroids)
- Provides formal framework: if you can prove your problem's feasible solutions form a matroid, greedy is guaranteed correct
- Trade-off: many problems don't form matroids but still admit greedy—need case-by-case analysis
Expected answer points:
- Kruskal's: sort all edges, iterate adding cheapest edge that doesn't create a cycle
- Cycle detection uses Union-Find (Disjoint Set Union) data structure
- Each vertex starts in its own set; adding an edge merges two sets
- Before adding edge (u,v), check if find(u) == find(v)—if true, edge creates cycle
- Union-Find with path compression and union by rank achieves near-constant amortized time
- Overall complexity: O(E log E) dominated by sorting
Expected answer points:
- Prim's: Grows one tree from a starting vertex, always adding cheapest edge connecting tree to new vertex (like Dijkstra but without path length accumulation)
- Kruskal's: Grows forest of trees, adding cheapest edge that connects any two different trees
- Prim's uses a frontier priority queue; Kruskal's processes all edges sorted by weight
- Prim's better for dense graphs (O(V²) with array, O(E log V) with heap)
- Kruskal's better for sparse graphs O(E log E)
- Both guarantee MST; choice depends on graph density and implementation
Expected answer points:
- Generate random test cases and compare greedy output to exhaustive/DP solution for small n
- Use known benchmark instances from literature where optimal values are documented
- Track solution quality ratio: greedy_result / optimal_result; should be close to 1.0
- Profile corner cases: clustered values, equal weights, adversarial orderings
- Statistical testing: run many instances, report minimum/median/5th percentile quality
- For production: continuously log quality metrics, alert if quality drops below threshold
Expected answer points:
- Complexity comes from the specific algorithm and its proof/data structure, not from the greedy paradigm; for example, activity selection sorts in O(n log n) and then scans in O(n)
- A heap-based implementation may pay for many priority-queue operations even when another data structure fits the input better
- Alternatively: greedy might be simple to state but implementation complexity is high
- Memory pressure: if greedy requires storing all possible choices, memory dominates runtime
- For small inputs, a simpler O(n²) method can outperform a sort-and-scan approach because its constants are lower
- Recommendation: benchmark with realistic data sizes, not just asymptotic analysis
Further Reading
- [Cormen et al., Introduction to Algorithms — Greedy Algorithms chapter]
- [GeeksforGeeks — Greedy Algorithms]
- [Visualgo — Algorithm visualization]
Conclusion
Greedy algorithms commit to local choices, so prove that each choice preserves an optimal solution before relying on the result. The activity-selection exchange argument shows why earliest finish is safe; the knapsack counterexample shows why a plausible ratio rule fails when items cannot be split. Runtime belongs to the particular algorithm and data structures: activity selection is O(n log n) when it must sort, or O(n) when already sorted. For 0/1 knapsack, choose a method whose cost fits the item count and capacity.
Category
Related Posts
Binary Search Variants: Beyond Simple Lookup
Choose binary search for monotone predicates and ternary search for unimodal objectives. Learn lower bounds, rotated-array search, and termination invariants.
Knapsack Problem Variants
Compare 0/1, unbounded, and fractional knapsack with dynamic programming solutions, loop-direction rules, memory estimates, and variant-specific examples.
Memoization vs Tabulation: Two Faces of Dynamic Programming
Understand the two fundamental DP approaches—top-down with memoization and bottom-up with tabulation—plus hybrid techniques like the/m on the fly.