Skip to main content

Exercises: Greedy Algorithms

These exercises review the two lessons on greedy algorithms. Most of them follow the same pattern: propose a selection criterion, then either prove that it is optimal or disprove it with a counterexample. Try each one before reading its solution: the solutions are grouped at the end of the page.


Choosing the criterion​

5.1. Activity selection. A meeting room receives requests for activities, each with a start and an end time. Two activities are compatible if they do not overlap (one may start exactly when the other ends). We want to accept as many activities as possible. Three greedy criteria are proposed: (a) earliest start first; (b) shortest duration first; (c) earliest end first. Find a counterexample for the criteria that are not optimal, and apply the optimal one to these 11 requests (start, end):

(1,4) (3,5) (0,6) (5,7) (3,9) (5,9) (6,10) (8,11) (8,12) (2,14) (12,16)

Solution to 5.1

5.2. How many rooms? Now all the activities must take place, and we want to use the fewest rooms. These are the lectures of a day (start and end, in hours):

9:00-10:30 9:00-12:30 9:00-10:30 11:00-12:30 11:00-14:00
13:00-14:30 13:00-14:30 14:00-16:30 15:00-16:30 15:00-16:30

How many rooms are needed? Describe a greedy algorithm that assigns the rooms and give its complexity.

Solution to 5.2

5.3. Refueling. A car can drive 400 km with a full tank. It must travel 1,000 km along a road with gas stations at kilometers 100, 250, 380, 500, 650, 800 and 950, and it starts with a full tank. Find the minimum number of stops, describe the greedy rule, and explain why it is optimal.

Solution to 5.3

5.4. Minimizing lateness. A machine must process six jobs, one at a time, without interruptions. Each job has a duration and a deadline; if a job ends after its deadline, its lateness is the difference. We want to minimize the maximum lateness.

Job123456
Duration321432
Deadline68991415

Would you order the jobs by duration, by slack (deadline minus duration), or by deadline? Give the resulting maximum lateness.

Solution to 5.4

Classic greedy algorithms​

5.5. Huffman coding. A file contains 100,000 characters drawn from six symbols with these frequencies (in thousands): a 45, b 13, c 12, d 16, e 9, f 5. Build a Huffman code (at each step, merge the two least frequent trees) and compute the size of the encoded file. Compare it with a fixed-length code.

Solution to 5.5

5.6. Kruskal. Apply Kruskal's algorithm (take the edges in increasing order of weight, discarding those that would form a cycle) to this undirected graph, and give the minimum spanning tree and its cost:

A-B 1 B-D 2 A-C 3 B-C 4 C-E 5 C-D 6 D-E 7 D-F 8 E-F 9

What data structure makes the cycle check efficient, and what is the total complexity?

Solution to 5.6

5.7. Dijkstra and negative weights. Dijkstra's algorithm, a greedy algorithm, finds shortest paths from a source when all the weights are non-negative. Build a graph with three nodes and one negative edge on which it gives a wrong answer, and explain which greedy decision fails.

Solution to 5.7

Counterexamples​

5.8. Coin systems. For which of these coin systems does the greedy change algorithm (always the largest coin that fits) give the minimum number of coins for every amount? For the others, find the smallest amount where it fails.

  • (a) 1, 3, 4
  • (b) 1, 2, 5
  • (c) 1, 7, 10
  • (d) the euro: 1, 2, 5, 10, 20, 50, 100, 200 cents

Solution to 5.8

5.9. Set cover. We want to choose the fewest sets from a family so that every element of a universe is in some chosen set. The greedy rule takes, at each step, the set that covers the most elements not yet covered. Show with a small example that it is not optimal.

Solution to 5.9


Solutions​

5.1.

  • (a) Earliest start fails with (0,10) (1,2) (3,4): it takes (0,10), which blocks the other two, while the optimum takes 2.
  • (b) Shortest duration fails with (0,5) (4,7) (6,11): it takes (4,7), which overlaps both of the others, while the optimum takes (0,5) and (6,11).
  • (c) Earliest end is optimal. Sorting by end time, it accepts (1,4), (5,7), (8,11) and (12,16): 4 activities. Checking all subsets confirms that no compatible set has 5. Why it works (exchange argument): let g1g_1 be the activity that ends first. In any optimal solution, replace its first activity with g1g_1: since g1g_1 ends no later, it is compatible with the rest, so there is an optimal solution that starts with the greedy choice; repeat with the remaining activities. Complexity: O(nlog⁡n)O(n \log n) for sorting plus O(n)O(n) for the scan.

Back to exercise 5.1

5.2. 3 rooms. That is the maximum number of lectures in progress at the same time (for example, the three that start at 9:00). No schedule can use fewer, because those lectures overlap; the greedy algorithm achieves it. Sort the lectures by start time and keep the rooms in a min-heap ordered by the time at which each becomes free. For each lecture, if the room that becomes free first is free at its start time, reuse it; otherwise, open a new room. O(nlog⁡n)O(n \log n). An equivalent check: sort the 2n2n start and end events by time (ends before starts at the same time) and track the number of lectures in progress; its maximum is the answer.

Back to exercise 5.2

5.3. 2 stops, at km 380 and km 650. The greedy rule: drive as far as possible, and stop at the last station reachable with the current fuel. From 0 the car reaches at most km 400, so it stops at 380; from there it reaches 780, so it stops at 650; from there it reaches 1,050, which is beyond the destination. Why it is optimal: after kk stops, the greedy car is at least as far along the road as any other strategy after kk stops (it "stays ahead"), so no strategy can finish with fewer stops. If two consecutive stations are more than 400 km apart, there is no solution, and the algorithm must detect it.

Back to exercise 5.3

5.4. By deadline (earliest deadline first). The order 1, 2, 3, 4, 5, 6 ends the jobs at times 3, 5, 6, 10, 13 and 15; only job 4 is late (it ends at 10 with deadline 9), so the maximum lateness is 1. Checking all 6!=7206! = 720 orders confirms that 1 is optimal. Ordering by duration ignores the deadlines (a short job with a distant deadline goes first), and ordering by slack also fails on small examples: with jobs (duration 1, deadline 2) and (duration 10, deadline 10), the slacks are 1 and 0, so the long job goes first and the short one ends at 11, 9 units late, while earliest deadline first gives a lateness of 1. The exchange argument: two consecutive jobs out of deadline order can be swapped without increasing the maximum lateness.

Back to exercise 5.4

5.5. The merges are: f (5) + e (9) = 14; c (12) + b (13) = 25; 14 + d (16) = 30; 25 + 30 = 55; a (45) + 55 = 100. The code lengths are 1 bit for a, 3 bits for b, c and d, and 4 bits for e and f. The encoded file has 45⋅1+(13+12+16)⋅3+(9+5)⋅4=22445 \cdot 1 + (13 + 12 + 16) \cdot 3 + (9 + 5) \cdot 4 = 224 thousand bits. A fixed-length code needs 3 bits per symbol (6 symbols), 300 thousand bits, so Huffman saves about 25%. Using a priority queue, building the code costs O(mlog⁡m)O(m \log m) for mm symbols. Huffman coding is used inside ZIP, gzip, PNG and JPEG.

Back to exercise 5.5

5.6. In increasing order: A-B 1 (accept), B-D 2 (accept), A-C 3 (accept), B-C 4 (reject: A, B and C are already connected), C-E 5 (accept), C-D 6 (reject), D-E 7 (reject), D-F 8 (accept). Five edges for six nodes, so the algorithm can stop: the tree has the edges A-B, B-D, A-C, C-E and D-F, with cost 19. The cycle check uses a union-find (disjoint sets) structure: an edge forms a cycle exactly when its two ends are already in the same set. With union by rank and path compression, each operation is almost O(1)O(1), and the total cost is dominated by sorting the edges: O(Elog⁡E)O(E \log E).

Back to exercise 5.6

5.7. Nodes A, B, C with edges A→B weight 2, A→C weight 3 and C→B weight −2, source A. Dijkstra first settles B with distance 2 (the closest node) and never revisits it. Then it settles C with distance 3, but the edge C→B would give B the distance 3−2=13 - 2 = 1, which is too late. The greedy decision "the closest unsettled node already has its final distance" relies on the fact that extending a path can never make it shorter, which is false with negative weights. For graphs with negative edges, Bellman-Ford (dynamic programming) is used.

Back to exercise 5.7

5.8. We compared greedy and optimal (computed by dynamic programming) for every amount up to 500.

  • (a) Fails. Smallest amount: 6, greedy 4 + 1 + 1 (3 coins), optimum 3 + 3 (2 coins).
  • (b) Optimal for every amount.
  • (c) Fails. Smallest amount: 14, greedy 10 + 1 + 1 + 1 + 1 (5 coins), optimum 7 + 7 (2 coins).
  • (d) Optimal for every amount. Coin systems for which greedy is always optimal are called canonical; most real currencies are designed to be canonical.

Back to exercise 5.8

5.9. Universe {1,2,3,4,5,6}\{1, 2, 3, 4, 5, 6\} and sets S1={1,2,3,4}S_1 = \{1, 2, 3, 4\}, S2={1,3,5}S_2 = \{1, 3, 5\}, S3={2,4,6}S_3 = \{2, 4, 6\}. Greedy first takes S1S_1 (4 new elements). Elements 5 and 6 remain, and it needs both S2S_2 and S3S_3: 3 sets. The optimum is S2S_2 and S3S_3: 2 sets. Set cover is NP-hard; the greedy algorithm is still useful because it is never worse than about ln⁡n\ln n times the optimum, and no polynomial algorithm is known to do much better.

Back to exercise 5.9

Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.