Sub topic 16
Matroids: Why Greedy Works When It Works
Earlier chapters proved each greedy algorithm correct on its own terms: one argument for activity selection, another for Kruskal, another for Huffman. This chapter asks a more general question. Is there a structural property of a problem that guarantees the greedy algorithm is optimal for every choice of weights? For a large family of problems the answer is yes, and the property is called a matroid.
This chapter assumes you have read the chapters on the exchange argument, greedy stays ahead, and minimum spanning trees. It also assumes you can follow a proof by contradiction and read Python that uses sets, sorting and union-find.
The Problem Greedy Is Really Solving
Many greedy problems share one shape:
- A finite ground set E of elements, such as the edges of a graph or the items for a knapsack.
- A rule that says which subsets are independent, meaning feasible. Examples are "contains no cycle" and "total weight fits the capacity."
- A weight w(x) for each element. The goal is an independent set with the largest total weight.
The generic greedy algorithm sorts the elements by weight, heaviest first, and adds each element if the chosen set stays independent. It never removes anything. The one problem-specific piece is the independence oracle, a function that answers "is this set feasible?"
The Definition
A set system (E, 𝓘), where 𝓘 is the family of independent sets, is a matroid if it satisfies three axioms:
- Non-empty: the empty set is independent.
- Hereditary: every subset of an independent set is independent.
- Exchange (augmentation): if A and B are independent and |A| < |B|, then some element x in B \ A makes A ∪ {x} independent.
The exchange axiom carries the weight. It says that a smaller feasible set can always grow by borrowing from a larger one. One consequence is that all maximal independent sets, called bases, have the same size. If two bases had different sizes, the smaller one could grow, so it would not be maximal.
Standard Examples
| Matroid | Ground set | Independent sets | Greedy algorithm you know |
|---|---|---|---|
| Uniform U(k, n) | any n items | subsets of size at most k | "take the k largest" |
| Graphic | edges of a graph | forests (acyclic edge sets) | Kruskal |
| Linear | vectors | linearly independent sets | choosing a max-weight basis of vectors |
| Partition | items in labeled groups | at most c_i items from group i | "best few from each category" |
The graphic matroid satisfies the exchange axiom for this reason. A forest A with |A| edges on n vertices has n − |A| connected components. A bigger forest B has fewer components, so some edge of B must join two different components of A. Adding that edge to A cannot create a cycle.
The Rado–Edmonds Theorem
Theorem. Let (E, 𝓘) be a hereditary set system that contains the empty set. The greedy algorithm finds a maximum-weight basis for every weight function exactly when (E, 𝓘) is a matroid.
The theorem has two directions. If the system is a matroid, greedy is always optimal. If the system is not a matroid, some weight function makes greedy fail.
Why Greedy Is Optimal on a Matroid
This direction is a greedy-stays-ahead proof. Greedy returns a basis G = g₁, g₂, …, gk in the order it picked them, so the weights do not increase. Let O = o₁, …, ok be an optimal basis sorted the same way. Both bases have size k. Suppose greedy is worse. Then at some first index i, w(oᵢ) > w(gᵢ).
Let A = {g₁, …, g{i−1}} and B = {o₁, …, oᵢ}. Since |A| < |B|, the exchange axiom gives some oj in B \ A with A ∪ {oj} independent. Its weight satisfies w(oj) ≥ w(oᵢ) > w(gᵢ), so greedy examined oj before gᵢ. At that moment greedy's chosen set was a subset of A. By the hereditary axiom, adding oj to that subset kept it independent, so greedy would have taken o_j. That contradicts the assumption that greedy skipped it. So for every i, w(gᵢ) ≥ w(oᵢ), and greedy's total weight is at least the optimum.
Why Greedy Fails on a Non-Matroid
Suppose exchange fails for some A and B. You can shrink B to |A| + 1 elements and exchange still fails, because B \ A only gets smaller. Let p = |A|. Assign these weights:
- Elements of A get weight p + 2.
- Elements of B \ A get weight p + 1.
- All other elements get weight 0.
Greedy takes all of A first. It cannot add anything from B \ A, so its useful weight is p(p + 2) = p² + 2p. The set B weighs at least (p + 1)² = p² + 2p + 1, which is strictly more. So greedy is not optimal.
Greedy With an Oracle, in Code
The function below implements the generic algorithm. Plugging in a forest test as the oracle and sorting by negated weight turns it into Kruskal. The result is a minimum-weight spanning tree, which is the maximum-weight basis under weights −w.
def matroid_greedy(elements, weight, is_independent):
chosen = []
for x in sorted(elements, key=weight, reverse=True):
if is_independent(chosen + [x]):
chosen.append(x)
return chosen
def is_forest(edges):
parent = {}
def find(x):
parent.setdefault(x, x)
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for u, v, _ in edges:
ru, rv = find(u), find(v)
if ru == rv:
return False
parent[ru] = rv
return True
edges = [(0, 1, 1), (0, 2, 4), (1, 2, 2), (1, 3, 6), (2, 3, 3)]
print(matroid_greedy(edges, lambda e: -e[2], is_forest))
# [(0, 1, 1), (1, 2, 2), (2, 3, 3)]The running time is O(n log n) for the sort plus n oracle calls. This oracle rebuilds a union-find on every call, so each call costs O(n). Real Kruskal keeps one union-find alive across all the calls, which is why it runs in O(m log m). The matroid view explains why the algorithm is correct. It does not tell you how to make the oracle fast.
Testing the Axioms by Brute Force
On small instances you can check the axioms directly. The checker below lists every independent set, then tests the hereditary and exchange axioms. Checking single-element removals is enough for heredity, because the property then follows by induction.
from itertools import combinations
def is_matroid(ground, independent):
family = [
frozenset(s)
for r in range(len(ground) + 1)
for s in combinations(ground, r)
if independent(set(s))
]
fam = set(family)
if frozenset() not in fam:
return False, ("empty set not independent",)
for A in family:
for x in A:
if A - {x} not in fam:
return False, ("hereditary", sorted(A), x)
for A in family:
for B in family:
if len(A) < len(B) and not any(A | {x} in fam for x in B - A):
return False, ("exchange", sorted(A), sorted(B))
return True, None
print(is_matroid(["a", "b", "c", "d"], lambda s: len(s) <= 2))
# (True, None)
triangle = [(0, 1, 0), (1, 2, 0), (0, 2, 0)]
print(is_matroid(triangle, lambda s: is_forest(list(s))))
# (True, None)
weights = {"a": 3, "b": 2, "c": 2}
print(is_matroid(["a", "b", "c"], lambda s: sum(weights[x] for x in s) <= 4))
# (False, ('exchange', ['a'], ['b', 'c']))The last call is a 0/1 knapsack with capacity 4. Its feasible sets are hereditary, but {a} cannot grow by borrowing from {b, c}. The theorem predicts a weight function that defeats greedy, and the knapsack's own values give one. With values a = 5, b = 3, c = 3, greedy by value takes a and then nothing fits, for a total of 5. The set {b, c} is worth 6. This is the structural reason 0/1 knapsack needs dynamic programming.
Gotchas and Boundaries
Not every correct greedy algorithm is a matroid algorithm. Activity selection, Huffman coding, minimizing lateness and Dijkstra are all correct, but none of them is "sort by a fixed weight and test independence." Compatible intervals are hereditary but fail exchange: {[0, 10]} cannot borrow from {[0, 4], [5, 9]}. Activity selection works because it uses the particular earliest-finish order, not arbitrary weights. Weighted interval scheduling, where each interval has a value, breaks greedy and needs DP. Some of these other algorithms are explained by broader structures such as greedoids. Others need their own proofs.
Fractional knapsack sits outside the model too. It allows fractional amounts of each item, so the ground set is not a set of whole elements. Its correctness comes from the exchange argument in its own chapter.
Intersections of matroids are usually not matroids. A bipartite matching must satisfy two partition matroids at once: each left vertex is used at most once, and each right vertex is used at most once. The intersection fails exchange, and greedy matching can be suboptimal. Weighted bipartite matching is solvable in polynomial time by matroid intersection or the Hungarian algorithm. Neither of those is a single greedy pass.
Feasibility versus optimality. The theorem covers greedy for every weight function. A non-matroid problem can still have special weights for which greedy happens to work. Coin change with US denominations is an example. Correctness then needs a proof specific to those weights.
Decision rule. For a new "pick a best feasible subset" problem, first ask whether feasibility is hereditary and has the exchange property. If yes, sort and test, and you are done. If exchange fails, look for a problem-specific greedy proof. If you cannot find one, use dynamic programming, or a greedy approximation when exact solutions are too expensive.
Exercise
Ground set E = {ax, ay, bx} is the edges of a bipartite graph with left vertices a, b and right vertices x, y. A set of edges is independent if it is a matching, meaning no two edges share a vertex. Show that this is not a matroid, then give weights for which greedy fails.
Show answer
The sets A = {ax} and B = {ay, bx} are both matchings with |A| < |B|. Adding ay to A shares vertex a, and adding bx shares vertex x, so exchange fails. Using the theorem's construction with p = 1, give ax weight 3 and ay, bx weight 2. Greedy takes ax for a total of 3, while {ay, bx} weighs 4.
Exercise
Partition the ground set into groups G1, ..., Gm. A set is independent if it has at most ci elements from each group Gi. Prove the exchange axiom.
Show answer
Let |A| < |B|. If |B ∩ Gi| ≤ |A ∩ Gi| held for every i, summing over all groups would give |B| ≤ |A|, a contradiction. So some group has |B ∩ Gi| > |A ∩ Gi|. That group contains an element x in B \ A. A has |A ∩ Gi| < |B ∩ Gi| ≤ c_i elements in that group, so A has room in it, and A ∪ {x} is independent.
Exercise
Modify matroid_greedy so it returns a maximum-weight independent set when some weights are negative, and explain why the modified version is still optimal on a matroid.
Show answer
Inside the loop, before the independence check, add "if weight(x) <= 0: break". Elements are sorted by decreasing weight, so every element after that point also has weight at most 0. Let O be an optimal independent set. Dropping its non-positive elements does not lower its weight, so assume O has only positive elements, say j of them. The greedy result restricted to positive elements is a basis of the matroid formed by the positive elements. The stays-ahead proof applies to that smaller matroid, so greedy's first j picks weigh at least as much as O, and any extra picks add positive weight.