14.25 Exercises
Greedy algorithms are best learned by proving, breaking, and implementing them.
14.25 Exercises
Greedy algorithms are best learned by proving, breaking, and implementing them. The code is usually short. The reasoning is where the work happens.
This final section collects exercises that reinforce the patterns from the chapter. Each problem asks you to identify the greedy choice, justify it, implement it, and analyze the result. Several exercises also ask for counterexamples, because a strong greedy designer must know how to disprove bad rules as well as prove good ones.
How to Use These Exercises
For each exercise, work through four steps:
1. State the greedy rule.
2. Prove or disprove the rule.
3. Implement the algorithm.
4. Analyze time and space complexity.
Do not skip the proof step. A greedy algorithm without a proof is only a heuristic.
Exercise 1: Maximum Non-Overlapping Intervals
Given intervals:
[1,3], [2,4], [3,5], [6,8], [7,9]
Select the maximum number of non-overlapping intervals.
Questions:
- Which sort key should be used?
- Which intervals are selected?
- Why does the greedy choice work?
- What is the time complexity?
Expected direction:
Sort by finish time.
Select the next compatible interval.
Exercise 2: Counterexample for Earliest Start
Show that sorting intervals by earliest start time does not always maximize the number of compatible intervals.
Construct the smallest example you can.
A useful shape is:
One long interval that starts early
Several short intervals that start later
Your answer should include:
- Input intervals
- Greedy output
- Optimal output
- Explanation of the failure
Exercise 3: Fractional Knapsack
Capacity:
W = 70
Items:
| Item | Weight | Value |
|---|---|---|
| A | 20 | 100 |
| B | 30 | 120 |
| C | 40 | 160 |
| D | 10 | 90 |
Tasks:
- Compute value density for each item.
- Sort items by density.
- Determine which fractions are taken.
- Compute total value.
- Prove why the density rule is safe.
Exercise 4: 0/1 Knapsack Counterexample
Using the same style as fractional knapsack, construct an example where choosing highest density first fails for 0/1 knapsack.
Your example should show:
Greedy value < Optimal value
Explain why the fractional exchange argument no longer applies.
Exercise 5: Job Sequencing with Deadlines
Jobs:
| Job | Deadline | Profit |
|---|---|---|
| A | 2 | 100 |
| B | 1 | 50 |
| C | 2 | 10 |
| D | 1 | 20 |
| E | 3 | 30 |
Each job takes one unit of time.
Tasks:
- Sort jobs by profit.
- Schedule each job as late as possible before its deadline.
- Return the final schedule.
- Compute total profit.
- Explain why late placement preserves flexibility.
Exercise 6: Minimum Refueling Stops
Input:
target = 100
startFuel = 25
stations = [
(25, 25),
(50, 25),
(75, 25)
]
Tasks:
- Simulate the max-heap algorithm.
- Count the minimum number of stops.
- Explain why choosing the largest passed station is optimal.
- Modify the input so the destination becomes unreachable.
Exercise 7: Course Scheduling
Courses:
| Course | Duration | Deadline |
|---|---|---|
| A | 5 | 5 |
| B | 4 | 6 |
| C | 2 | 6 |
| D | 1 | 7 |
Tasks:
- Sort by deadline.
- Add courses one at a time.
- When total duration exceeds the deadline, remove the longest course.
- Return the accepted courses.
- State the invariant maintained by the algorithm.
Exercise 8: Huffman Coding
Frequencies:
| Symbol | Frequency |
|---|---|
| A | 5 |
| B | 9 |
| C | 12 |
| D | 13 |
| E | 16 |
| F | 45 |
Tasks:
- Build the Huffman tree manually.
- Record each merge.
- Compute the final weighted path length.
- Explain why the two lowest frequencies can be siblings.
- Implement the algorithm with a min-heap.
Exercise 9: Remove K Digits
Input:
num = "10200"
k = 1
Tasks:
- Simulate the monotonic stack.
- Remove leading zeros from the result.
- Return the smallest possible number.
- Explain why popping a larger previous digit is safe.
Then repeat for:
num = "1432219"
k = 3
Exercise 10: Partition Labels
Input:
ababcbacadefegdehijhklij
Tasks:
- Compute the last occurrence of each character.
- Scan left to right.
- Track the current partition boundary.
- Return the partition lengths.
- Explain why closing the partition at the boundary is safe.
Exercise 11: Rescue Boats
Input:
people = [3, 2, 2, 1]
limit = 3
Tasks:
- Sort the weights.
- Use two pointers.
- Count the boats.
- Prove why the heaviest person can be handled immediately.
- Give a counterexample to the rule "always pair the two lightest people."
Exercise 12: Lemonade Change
Input:
[5, 5, 10, 10, 20]
Tasks:
- Simulate the algorithm.
- Determine whether change can be made for every customer.
- Explain why using
10 + 5is preferred over5 + 5 + 5. - Give an input where the algorithm fails because change is impossible.
Exercise 13: Minimum Platforms
Arrivals:
900, 940, 950, 1100, 1500, 1800
Departures:
910, 1200, 1120, 1130, 1900, 2000
Tasks:
- Sort arrivals and departures.
- Sweep through events.
- Track active trains.
- Return the maximum active count.
- Explain why maximum simultaneous demand is a lower bound and also sufficient.
Exercise 14: Kruskal's Algorithm
Graph edges:
| Edge | Weight |
|---|---|
| A-B | 4 |
| A-C | 1 |
| B-C | 3 |
| B-D | 2 |
| C-D | 5 |
Tasks:
- Sort edges by weight.
- Use union-find to select safe edges.
- Return the minimum spanning tree.
- Compute total weight.
- Prove correctness using the cut property.
Exercise 15: Dijkstra's Greedy Choice
Given a graph with nonnegative edge weights, explain why the vertex with the smallest tentative distance can be finalized.
Then answer:
- What breaks if negative edges are allowed?
- Give a small graph where Dijkstra fails with a negative edge.
- Which algorithm can handle negative edges?
Exercise 16: Coin Change Counterexample
Coins:
4, 3, 1
Amount:
6
Tasks:
- Run the largest-coin greedy algorithm.
- Compute the optimal solution.
- Explain why the greedy remainder is bad.
- Find another noncanonical coin system where greedy fails.
Exercise 17: Maximum Units on a Truck
Input:
boxTypes = [
[5, 10],
[2, 5],
[4, 7],
[3, 9]
]
truckSize = 10
Tasks:
- Sort by units per box.
- Load boxes greedily.
- Compute total units.
- Prove correctness using an exchange argument.
Exercise 18: Reorganize String
Input:
aaabbc
Tasks:
- Count character frequencies.
- Use a max-heap to construct a valid string.
- Explain why the most frequent character should be used early.
- Determine when no valid answer exists.
Exercise 19: Greedy or Dynamic Programming?
Classify each problem as usually greedy, dynamic programming, or not generally solvable exactly by either simple method:
| Problem | Classification |
|---|---|
| Fractional knapsack | ? |
| 0/1 knapsack | ? |
| Interval scheduling | ? |
| Weighted interval scheduling | ? |
| Coin change with arbitrary coins | ? |
| Minimum spanning tree | ? |
| Traveling salesman | ? |
For each, give one sentence explaining the classification.
Exercise 20: Design Your Own Greedy Rule
Choose one of these domains:
- Scheduling
- Resource allocation
- String construction
- Graph optimization
- Compression
Define:
- Input model
- Objective
- Greedy rule
- Data structure
- Correctness argument or counterexample
The exercise is complete only when you either prove the greedy rule or produce a counterexample.
Reference Answers
Use these only after attempting the exercises.
Exercise 1
Sort by finish time.
Selected:
[1,3], [3,5], [6,8]
or another compatible maximum set depending on endpoint convention.
Maximum count:
3
Exercise 3
Densities:
| Item | Density |
|---|---|
| A | 5 |
| B | 4 |
| C | 4 |
| D | 9 |
Order:
D, A, B, C
Take:
D fully
A fully
B fully
10/40 of C
Total:
90 + 100 + 120 + 40 = 350
Exercise 5
Profit order:
A, B, E, D, C
One optimal schedule:
| Slot | Job |
|---|---|
| 1 | B |
| 2 | A |
| 3 | E |
Total profit:
180
Exercise 6
Stops:
3
The car refuels at every station.
If the first station is moved from position 25 to position 26, the destination is unreachable.
Exercise 8
Merge order:
5 + 9 = 14
12 + 13 = 25
14 + 16 = 30
25 + 30 = 55
45 + 55 = 100
This is the classical Huffman construction.
Exercise 11
Sorted:
[1,2,2,3]
Boats:
3
The heaviest person 3 cannot pair with 1 because 3 + 1 > 3, so 3 must go alone.
Exercise 14
Sorted edges:
A-C(1), B-D(2), B-C(3), A-B(4), C-D(5)
Selected:
A-C, B-D, B-C
Total weight:
6
Takeaway
Exercises are where greedy reasoning becomes reliable. For each problem, identify the local rule, attack it with counterexamples, prove it with exchange or structural arguments, and then choose the simplest data structure that implements it efficiently. Greedy algorithms are short because their implementations are compact, not because their reasoning is trivial.