Sub topic 15
Greedy Approximation: Set Cover and Beyond
The earlier chapters used greedy algorithms that always find the best answer. This chapter covers problems where no fast algorithm is known to find the best answer, and where most researchers believe none exists. For these problems a greedy rule can still give an answer that is provably close to the best. You will learn the greedy algorithm for set cover, the proof that it is never worse than about ln n times the optimum, and how to recognize when a greedy approximation is the right tool.
This chapter assumes you know:
- the greedy choice property and the exchange argument from earlier chapters,
- the counterexample habit from the coin change chapter,
- Python sets and the meaning of NP-hard. An NP-hard problem is one for which no polynomial-time exact algorithm is known.
Approximation Ratios
An approximation algorithm runs in polynomial time and returns a feasible solution with a guarantee attached. For a minimization problem, an algorithm has approximation ratio ρ if, on every input, its cost is at most ρ × OPT, where OPT is the cost of the optimal solution. For a maximization problem, its value is at least ρ × OPT, with ρ ≤ 1.
The guarantee must hold for every input. An algorithm that does well on typical data has no ratio unless that behavior is proved. You prove a ratio the same way you proved exactness earlier: compare greedy's choices with an unknown optimal solution. The difference is that the proof now bounds a gap. It does not show the gap is zero.
The Set Cover Problem
You are given a universe U of n elements and a collection of subsets S₁, …, Sₘ of U. Each subset has a cost, which is 1 in the unweighted version. The task is to choose subsets whose union is U at the lowest total cost.
Set cover appears under many names. Examples include choosing the fewest fire stations so every district is served, picking test cases that cover every code branch, and selecting sensors that watch every zone. It is NP-hard.
The greedy rule
At each step, choose the set with the lowest cost per newly covered element. In the unweighted case this is the set that covers the most elements still uncovered. Repeat until nothing is left uncovered.
def greedy_set_cover(universe, subsets, costs=None):
if costs is None:
costs = [1] * len(subsets)
uncovered = set(universe)
chosen = []
while uncovered:
best, best_ratio = None, float("inf")
for i, s in enumerate(subsets):
new = len(s & uncovered)
if new > 0 and costs[i] / new < best_ratio:
best, best_ratio = i, costs[i] / new
if best is None:
return None # some element is in no subset
chosen.append(best)
uncovered -= subsets[best]
return chosen
subsets = [{1, 2, 3}, {4, 5, 6}, {1, 2, 4, 5}]
print(greedy_set_cover(range(1, 7), subsets)) # [2, 0, 1]The example is a counterexample built for the purpose. The optimal cover is sets 0 and 1, which is two sets. Greedy is drawn to set 2 because it covers four elements. After that, elements 3 and 6 sit in different sets, so greedy needs three sets. If you stack copies of this trap, with the decoy sets halving in size each time, the gap grows to about log₂ n. Greedy is not exact, and you can also see that its ratio cannot be a constant.
Each round scans all m sets and does a set intersection, so this simple version runs in O(m · Σ|Sᵢ|) time in the worst case. A lazy priority queue brings it close to O(Σ|Sᵢ| log m) in practice. Re-insert a set with its updated count only when it reaches the top of the queue with a stale count.
Proving the ln n Bound
The proof uses a pricing argument. Each time greedy picks a set S at cost c(S) that covers k new elements, give each of those elements the price c(S)/k. The prices of all elements add up to greedy's total cost.
Now fix any set S from the optimal solution, and list its elements in the order greedy covers them: e₁, e₂, …, e_d. Just before eᵢ is covered, at least d − i + 1 elements of S are still uncovered. At that moment greedy could have picked S itself at cost per new element of at most c(S)/(d − i + 1). Greedy picks the cheapest ratio available, so
price(eᵢ) ≤ c(S*) / (d − i + 1).
Summing over the elements of S* gives
Σ price(eᵢ) ≤ c(S) · (1 + 1/2 + … + 1/d) = c(S) · H(d),
where H(d) is the d-th harmonic number, about ln d + 0.577. Every element lies in at least one optimal set. So greedy's total cost is at most the sum of these bounds over all optimal sets:
greedy ≤ H(d_max) · OPT ≤ (ln n + 1) · OPT,
where d_max is the size of the largest subset.
Is ln n good enough?
Usually it is the best you can get. Feige (1998) showed that no polynomial-time algorithm achieves (1 − ε) ln n for set cover unless NP has quasi-polynomial-time algorithms. Dinur and Steurer (2014) later strengthened this to "unless P = NP." So the simplest algorithm is, up to lower-order terms, the best possible one. On real data greedy often lands within a few percent of optimal, because its worst-case instances are artificial.
Beyond Set Cover
The same style of thinking gives approximations for many problems. The table lists the common ones.
| Problem | Greedy rule | Guarantee | Known limit |
|---|---|---|---|
| Set cover | Lowest cost per new element | H(d) ≤ ln n + 1 | (1 − ε) ln n is NP-hard |
| Max coverage, k sets | Most new elements, k times | ≥ (1 − 1/e) · OPT ≈ 0.632 | Better is NP-hard |
| Monotone submodular, cardinality k | Largest marginal gain | ≥ (1 − 1/e) · OPT | Same |
| Vertex cover | Take both ends of an uncovered edge | ≤ 2 · OPT | About 1.36 is NP-hard; 2 under the Unique Games Conjecture |
| Vertex cover | Highest-degree vertex first | Only Θ(log n) | — |
| Load balancing | Next job to least-loaded machine | ≤ 2 · OPT (4/3 if jobs sorted largest first) | — |
Maximum coverage and submodularity
Suppose you may pick only k sets and want to cover as many elements as possible. Run the set cover loop for k rounds. The guarantee 1 − 1/e comes from one fact. After each pick, the remaining gap to OPT shrinks by at least a 1/k fraction, so after k picks the gap is at most (1 − 1/k)ᵏ ≤ 1/e of OPT.
Coverage depends on only one property, diminishing returns: adding a set helps less when more is already covered. Functions with this property are called submodular. The same greedy algorithm and the same 1 − 1/e bound apply to sensor placement, document summarization and influence maximization in social networks.
Vertex cover: the obvious greedy is the wrong one
A vertex cover is a set of vertices that touches every edge. The intuitive rule, "take the highest-degree vertex," is a set cover greedy. On bad graphs it is off by a log n factor. A less obvious rule does better.
def vertex_cover_2approx(edges):
cover = set()
for u, v in edges:
if u not in cover and v not in cover:
cover.update((u, v))
return cover
print(vertex_cover_2approx([(1, 2), (2, 3), (3, 4)])) # {1, 2, 3, 4}Each time this algorithm adds a pair, the edge (u, v) shares no endpoint with any earlier picked edge, so the picked edges form a matching. Any cover must contain at least one endpoint of each matching edge. That gives OPT ≥ |matching|, while the algorithm takes exactly 2 × |matching| vertices. The path example reaches this bound: the optimum is {2, 3}, and the algorithm returns four vertices.
Common Errors
- Claiming a ratio from experiments. Ten good runs prove nothing. The ratio is a worst-case statement that needs a proof.
- Ignoring costs in weighted set cover. Picking the set with the most new elements, without dividing by cost, has no bounded ratio. One huge expensive set can beat many cheap small ones.
- Forgetting the infeasible case. If some element is in no subset, the loop never ends unless you check for zero progress, as the code above does.
- Using the wrong greedy. As vertex cover shows, the most natural local rule can be much worse than a slightly different one. Test candidate rules against small adversarial inputs, as in the coin change chapter.
- Confusing ratio direction. For maximization a ratio of 0.632 means "at least 63.2% of optimal." For minimization a ratio of 2 means "at most twice optimal."
Choosing Greedy Approximation
Use a greedy approximation when all of the following hold:
- The problem is NP-hard, or the exact method (dynamic programming, integer programming) does not scale to your input size.
- You can name a lower bound on OPT, for minimization, or an upper bound, for maximization, that greedy's choices can be charged against.
- The proven ratio, or the gap you observe in practice, is acceptable for the application.
If inputs are small, an integer-programming solver may find the true optimum in seconds. If they are large, greedy's speed and its near-optimal worst-case guarantee are hard to beat.
Exercise
Weighted set cover on U = {1, 2, 3, 4} with sets A = {1, 2, 3, 4} costing 5, B = {1, 2} costing 1, and C = {3, 4} costing 3. What does the greedy rule pick, what does it cost, and what is OPT?
Show answer
Initial cost per new element: A = 5/4 = 1.25, B = 1/2 = 0.5, C = 3/2 = 1.5. Greedy picks B. Remaining {3, 4}: A = 5/2 = 2.5, C = 3/2 = 1.5, so greedy picks C. Total cost 4, which is optimal here (A alone costs 5). Greedy is often optimal on small inputs. The ratio only bounds how bad it can get.
Exercise
Show that the bound H(d) is reached in the limit. Build an unweighted family where greedy uses about log₂ n sets but OPT is 2.
Show answer
Arrange n = 2(2^k − 1) elements in two rows of 2^k − 1 elements each. The two rows are the optimal cover, so OPT = 2. Add decoy sets D₁, …, Dk, where Dᵢ takes 2^(i−1) columns from both rows, so it has 2^i elements. Greedy first picks Dk, which has 2^k elements and beats each row's 2^k − 1. It then keeps picking the largest remaining decoy, which ties each row's remaining count; break the ties toward the decoys, or shrink each row by one element to make the choice strict. Greedy uses k ≈ log₂ n sets against OPT = 2.
Exercise
A colleague proposes this vertex cover rule: repeatedly pick any uncovered edge and add only its endpoint of higher degree. Does this keep the factor-2 guarantee?
Show answer
No. The factor-2 proof needs both endpoints so it can charge 2 vertices to each matching edge, which OPT must also hit. Adding one endpoint reduces the rule to a degree-based heuristic that can be off by Θ(log n). The proof no longer applies, and adversarial graphs exist where the rule does badly.