Sub topic 2
The Greedy Choice Property
This chapter assumes you can read and run Python functions that use sorting and itertools, and that you know what an "optimal solution" means for an optimization problem. Proofs by contradiction come up briefly. The full proof techniques are covered in later chapters.
A greedy algorithm makes one choice, commits to it, and then solves what remains. That approach only works when the first choice is safe, meaning it never rules out reaching an optimal answer. The greedy choice property is the formal name for that safety condition. This chapter defines it, shows how to test a candidate greedy rule against it, and explains the mistakes people make when they claim a problem has it.
The Definition
A problem has the greedy choice property for a particular selection rule when the following holds: for every instance, at least one optimal solution includes the element the rule picks first.
There are three things to notice in that sentence.
- The property belongs to a rule, not to a problem. Interval scheduling has the property under "earliest finish time" and lacks it under "earliest start time." Saying "this problem is greedy" without naming the rule says nothing.
- "At least one" optimal solution, not every one. An instance can have many optimal solutions. Most of them may leave out the greedy pick. You only need one that keeps it.
- "For every instance." A rule that works on the examples you tried but fails on one other input does not have the property.
A choice that satisfies this condition is often called a safe choice. Once you make it, the best answer still available to you is as good as the best answer overall.
The loop in the diagram also shows why the greedy choice property cannot work alone. After the first commitment you face a smaller instance, and the rule has to be safe there as well. That requirement, that an optimal answer to the whole is "greedy pick plus optimal answer to the rest," is optimal substructure. It is the subject of the next chapter.
Where the Choice Happens: Greedy versus Dynamic Programming
Dynamic programming also builds optimal solutions from optimal sub-solutions, but it decides at a different point.
| Aspect | Dynamic programming | Greedy with the greedy choice property |
|---|---|---|
| When the choice is made | After solving all relevant subproblems | Before solving any subproblem |
| How many subproblems per step | Several, one per possible choice | Exactly one |
| What justifies the choice | Comparing the computed options | A proof that the rule's pick is always safe |
| Typical cost | Polynomial in the size of the subproblem table | Often one sort plus a linear scan |
The greedy choice property lets you skip the comparison step entirely. You don't need to evaluate the alternatives because a proof has already shown that your pick does at least as well as any of them.
Testing Candidate Rules on Interval Scheduling
In interval scheduling you get a set of intervals (start, end), and the goal is to choose as many as possible with no two overlapping. Intervals that touch at an endpoint, such as (1, 3) and (3, 5), count as compatible. Four rules sound reasonable:
- Earliest start time first.
- Shortest interval first.
- Fewest conflicts first (the interval that overlaps the fewest others).
- Earliest finish time first.
Each rule describes a greedy algorithm: sort by the rule, then take every interval that is compatible with the ones already taken. To find out whether a rule has the greedy choice property, look for an instance where it does worse than the optimum. A brute-force solver gives you that optimum on small inputs.
from itertools import combinations
def overlaps(a, b):
return a[0] < b[1] and b[0] < a[1]
def compatible(subset):
s = sorted(subset, key=lambda iv: iv[1])
return all(x[1] <= y[0] for x, y in zip(s, s[1:]))
def best_size(intervals):
for k in range(len(intervals), 0, -1):
for subset in combinations(intervals, k):
if compatible(subset):
return k
return 0
def greedy(intervals, key):
chosen = []
for iv in sorted(intervals, key=key):
if all(not overlaps(iv, c) for c in chosen):
chosen.append(iv)
return len(chosen)
def by_start(intervals):
return lambda iv: iv[0]
def by_length(intervals):
return lambda iv: iv[1] - iv[0]
def by_conflicts(intervals):
# subtract 1 so an interval does not count itself
return lambda iv: sum(overlaps(iv, other) for other in intervals) - 1
def by_finish(intervals):
return lambda iv: iv[1]
cases = {
"earliest start": (by_start, [(0, 10), (1, 2), (3, 4)]),
"shortest": (by_length, [(0, 5), (4, 6), (5, 10)]),
"fewest conflicts": (by_conflicts, [
(0, 2), (2, 4), (4, 6), (6, 8),
(1, 3), (1, 3), (1, 3),
(3, 5),
(5, 7), (5, 7), (5, 7),
]),
}
for name, (rule, intervals) in cases.items():
print(f"{name:17} rule={greedy(intervals, rule(intervals))} "
f"finish={greedy(intervals, by_finish(intervals))} "
f"optimum={best_size(intervals)}")
# earliest start rule=1 finish=2 optimum=2
# shortest rule=1 finish=2 optimum=2
# fewest conflicts rule=3 finish=4 optimum=4Each counterexample breaks its rule at the first choice:
- Earliest start picks
(0, 10). No optimal solution contains it, because both optimal solutions use(1, 2)and(3, 4). - Shortest picks
(4, 6). It overlaps both of the other intervals, and the only optimal solution is{(0, 5), (5, 10)}. - Fewest conflicts picks
(3, 5), which has only two conflicts. The unique optimum is the row(0, 2), (2, 4), (4, 6), (6, 8), and(3, 5)overlaps two intervals in that row.
In all three cases the first pick is unsafe. That is exactly the failure of the greedy choice property. Earliest finish matches the optimum in every case, which is evidence, not proof.
Proving the Property for Earliest Finish
Proofs of the greedy choice property usually follow the same pattern: start from any optimal solution and turn it into one that contains the greedy pick without making it worse.
Claim. Let g be the interval with the earliest finish time. Some maximum-size compatible set contains g.
Sketch. Take any optimal set O and sort it by finish time. Call its first interval f. If f = g, you are done. If not, g finishes no later than f, because g has the earliest finish of all intervals. Every other interval in O starts at or after f ends, which means it also starts at or after g ends. Replacing f with g therefore gives a compatible set of the same size. That set is optimal and contains g.
This swap is a small exchange argument. The chapters on greedy-stays-ahead and on the exchange argument turn this pattern into general techniques. For now, notice its shape: the proof never builds an optimal solution. It takes an arbitrary optimal solution and shows that it can be adjusted to agree with the greedy pick.
Common Mistakes
Confusing "best-looking" with "safe"
Every greedy rule picks something that looks best by some measure. The greedy choice property asks whether that pick survives in an optimal solution. The shortest interval looks least costly, but the earlier counterexample shows it is not safe.
Claiming the pick appears in every optimal solution
If you try to prove the stronger claim, you will often get stuck, because it is usually false. For intervals (0, 2), (1, 3), (3, 4), both {(0, 2), (3, 4)} and {(1, 3), (3, 4)} are optimal. Only the first contains the greedy pick (0, 2), and that one solution is all the property needs.
Ignoring tie-breaking
When two elements tie under the rule, the proof has to cover whichever one the code picks. For earliest finish, any interval with the minimum finish time works, because the swap argument only uses "finishes no later than f." Some rules need a specific tie-break. When a proof covers only one tie-break, state that tie-break in the code. Python's sorted is stable, so ties keep their input order unless the key also includes a secondary field.
Proving safety only for the first step
The proof above covers the first pick on the original input. The algorithm makes later picks on smaller inputs, so the argument has to apply to those inputs too. For interval scheduling it does, because the remaining intervals form an ordinary instance of the same problem. You will check that formally with optimal substructure.
Exercise
Consider the rule "latest start time first" for interval scheduling, where you scan intervals in decreasing order of start time and take each compatible one. Does it have the greedy choice property? Justify your answer.
Show answer
Yes. It is the mirror image of earliest finish. Reverse time by mapping each interval (s, e) to (-e, -s). Latest start becomes earliest finish, and compatibility is preserved, so the same swap argument applies. Concretely: let g have the latest start and let f be the interval with the latest start in some optimal set O. Every other interval in O ends at or before f starts, which is at or before g starts. Replacing f with g keeps O compatible and the same size.
Exercise
A student says: "Rule R has the greedy choice property because, on the instance I tested, every optimal solution contained R's first pick." Name two separate flaws in this argument.
Show answer
First, the property must hold for every instance, and one instance proves nothing about the others. Second, the student checked a stronger and unnecessary condition (every optimal solution contains the pick) instead of the actual requirement (at least one does). Showing the strong condition on one input neither proves the property in general nor reflects what a proof would need to establish.
Exercise
Run greedy([(0, 3), (2, 5), (4, 7), (1, 8)], byconflicts(...)) using the code in this chapter, and compare it with bestsize on the same list. Before running it, work out each interval's conflict count by hand and predict the result.
Show answer
The conflict counts are (0, 3): 2 [with (2, 5) and (1, 8)], (2, 5): 3, (4, 7): 2, (1, 8): 3. The sort is stable, so the rule picks (0, 3) and then (4, 7). Both remaining intervals overlap one of those two. The greedy result is 2 and best_size is also 2, so this instance is not a counterexample. That is a reminder that the rule can match the optimum on many inputs and still lack the property.