Greedy Algorithms

How greedy algorithms build an answer from locally best choices, how to prove a greedy rule is correct, and what interviewers ask about it.

14 minLesson 2 of 5
On this page
  1. Scheduling the most bookings in one room
  2. Why the earliest end time is correct
  3. Variants and where greedy stops working
  4. How to tell whether a greedy rule is correct
  5. Pitfalls
  6. In the interview
  7. What to practise next

A greedy algorithm builds a solution one step at a time. At each step it takes the choice that looks best at that moment, and it never goes back to change an earlier choice. It is used for optimization problems such as scheduling, selecting and covering, where trying every combination would be too slow. You reach for it when sorting the input by a well-chosen rule lets a single pass produce the best answer.

The difficulty is that a greedy rule is only a guess until it has been proven. Taking the largest coin that fits gives the fewest coins for 25, 10, 5 and 1, but with coins of 4, 3 and 1 it makes 6 from three coins (4 + 1 + 1) when two are enough (3 + 3). Most of the work in a greedy problem is choosing the rule and checking that it is correct.

Scheduling the most bookings in one room

The standard example is a meeting room with a list of booking requests, each with a start hour and an end hour. You want to accept as many requests as possible, with no two overlapping. A booking that ends at 6 and one that starts at 6 do not overlap.

Three rules look reasonable: take the shortest booking first, take the earliest start first, or take the booking that ends earliest. Only the last one is always correct, because a booking that ends early leaves the room free for the longest time afterwards. The algorithm is to sort the bookings by end time, go through them in order, and keep a booking whenever it starts at or after the end of the last booking you kept.

Fit the most bookings into one roomUse the arrows or ← → keys
sort bookings by end timefor each (start, end) in order:  if start < lastEnd: skip  else: keep it; lastEnd = end
  1. bookings
    01–3
    12–5
    24–6
    31–7
    46–8
    57–9
    lastEnd
    −∞
    kept
    0

    1The bookings are sorted by end time. Nothing has been kept yet, so lastEnd starts at minus infinity.

  2. bookings
    01–3i
    12–5
    24–6
    31–7
    46–8
    57–9
    lastEnd
    3
    kept
    1

    2The booking 1–3 starts after minus infinity, so it fits. We keep it, and the room is busy until 3.

  3. bookings
    01–3
    12–5i
    24–6
    31–7
    46–8
    57–9
    lastEnd
    3
    kept
    1

    3The booking 2–5 starts at 2, but the room is busy until 3, so we skip it.

  4. bookings
    01–3
    12–5
    24–6i
    31–7
    46–8
    57–9
    lastEnd
    6
    kept
    2

    4The booking 4–6 starts at 4, which is after 3, so we keep it, and the room is busy until 6.

  5. bookings
    01–3
    12–5
    24–6
    31–7i
    46–8
    57–9
    lastEnd
    6
    kept
    2

    5The booking 1–7 starts at 1, long before 6, so we skip it.

  6. bookings
    01–3
    12–5
    24–6
    31–7
    46–8i
    57–9
    lastEnd
    8
    kept
    3

    6The booking 6–8 starts exactly at 6. Back-to-back bookings are allowed, so we keep it.

  7. bookings
    01–3
    12–5
    24–6
    31–7
    46–8
    57–9i
    lastEnd
    8
    kept
    3

    7The booking 7–9 starts at 7, but the room is busy until 8, so we skip it.

  8. bookings
    01–3
    12–5
    24–6
    31–7
    46–8
    57–9
    lastEnd
    8
    kept
    3

    8The scan is finished with 3 bookings kept (1–3, 4–6 and 6–8). It needed one pass after the sort.

1 / 8
// bookings: [start, end] pairs. Back-to-back bookings are allowed.
function maxBookings(bookings) {
  const byEnd = [...bookings].sort((a, b) => a[1] - b[1]);
  let kept = 0;
  let lastEnd = -Infinity;
  for (const [start, end] of byEnd) {
    if (start >= lastEnd) { // fits after the last booking we kept
      kept++;
      lastEnd = end;
    }
  }
  return kept;
}
 
maxBookings([[2, 5], [6, 8], [1, 3], [1, 7], [4, 6], [7, 9]]); // 3
# bookings: [start, end] pairs. Back-to-back bookings are allowed.
def max_bookings(bookings):
    by_end = sorted(bookings, key=lambda b: b[1])
    kept = 0
    last_end = float("-inf")
    for start, end in by_end:
        if start >= last_end:  # fits after the last booking we kept
            kept += 1
            last_end = end
    return kept
 
max_bookings([[2, 5], [6, 8], [1, 3], [1, 7], [4, 6], [7, 9]])  # 3
TimeO(n log n)
SpaceO(n)

The sort dominates and the scan is O(n). The space is the sorted copy of the input.

Why the earliest end time is correct

Checking that a rule works on a few examples does not prove it, because the wrong rules above also work on many inputs. The usual proof is an exchange argument.

Let X be the booking that ends first. Take any best schedule and look at its first booking, Y. Y cannot end before X, because X ends first. Replace Y with X. Since X ends no later than Y, it cannot overlap anything that came after Y, so the schedule is still valid and has the same number of bookings. This shows that some best schedule starts with X, so choosing X is never a mistake. What remains is the same problem on the bookings that start at or after the end of X, and the same argument applies to it again.

The same swap fails for the other two rules, which is how you can tell they are wrong. With bookings 1–10, 2–3 and 4–5, the earliest-start rule takes 1–10 and blocks both short bookings, so it keeps 1 where 2 are possible. With bookings 1–5, 4–7 and 6–10, the shortest-first rule takes 4–7, which overlaps both of the others, so it keeps 1 where 2 are possible.

Variants and where greedy stops working

Coin change

Making an amount from the fewest coins by always taking the largest coin that fits is greedy. For coins of 25, 10, 5 and 1 it is always optimal, so the 63 cents in change is 25, 25, 10, 1, 1, 1, which is six coins. For other coin sets the exchange argument fails: with coins 4, 3 and 1 and an amount of 6, replacing one 3 of the best answer (3 + 3) by the greedy 4 gives 7, which is too much. The first coin changes what is left to solve, and greedy never looks ahead.

Greedy 3 coins 4 1 1 = 6 Best 2 coins 3 3 = 6
Making 6 from coins 4, 3 and 1. The greedy first choice of 4 leads to three coins, while two coins of 3 are enough.
Greedy change: correct for some coin sets and wrong for others
// coins sorted from largest to smallest
function greedyChange(coins, amount) {
  let used = 0;
  for (const coin of coins) {
    while (amount >= coin) {
      amount -= coin;
      used++;
    }
  }
  return amount === 0 ? used : -1; // -1: greedy got stuck
}
 
greedyChange([25, 10, 5, 1], 63); // 6, the true minimum
greedyChange([4, 3, 1], 6);       // 3, but 3 + 3 needs only 2
# coins sorted from largest to smallest
def greedy_change(coins, amount):
    used = 0
    for coin in coins:
        while amount >= coin:
            amount -= coin
            used += 1
    return used if amount == 0 else -1  # -1: greedy got stuck
 
greedy_change([25, 10, 5, 1], 63)  # 6, the true minimum
greedy_change([4, 3, 1], 6)        # 3, but 3 + 3 needs only 2

The code is identical in both cases, and only the coin set decides whether it is correct. When the coins are arbitrary, use dynamic programming, which solves every smaller amount instead of committing to one coin.

Fractional knapsack and 0/1 knapsack

In the fractional knapsack you have a bag with a weight limit and items with a value and a weight, and you may take part of an item. The greedy rule is to sort the items by value per unit of weight and take them in that order, splitting the last one if it does not fit. With a limit of 50 and items of (value, weight) (60, 10), (100, 20) and (120, 30), the ratios are 6, 5 and 4. You take the first two completely for a value of 160, then 20 of the 30 units of the third item for another 80, which gives 240. The rule is correct because any weight spent on a lower-ratio item could be spent on a higher-ratio one for more value.

In the 0/1 knapsack each item is taken whole or not at all, and the same rule fails. It takes the first two items for 160 and cannot fit the third, but the second and third items together weigh exactly 50 and are worth 220. The ability to split an item is what made the exchange argument work, so without it the problem needs dynamic programming.

Jump game

Given an array where each number is the farthest you can jump from that position, decide whether you can reach the last index. The greedy approach scans from left to right and keeps the farthest index reachable so far. If the scan reaches an index beyond that value, the end is unreachable. For [2, 3, 1, 1, 4] the farthest reach is 2 at index 0 and 4 at index 1, which is the last index, so the answer is yes. For [3, 2, 1, 0, 4] the farthest reach never exceeds 3, so index 4 cannot be reached. It needs only one pass and no search over jump choices, because the set of reachable positions is always a prefix of the array and a single number describes it.

How to tell whether a greedy rule is correct

  1. Look for a counterexample first. Try small inputs built to break the rule, such as a long booking that starts early or a large coin that leaves an awkward remainder. Most wrong rules fail within a minute.
  2. Try the exchange argument. Swap the greedy choice into an arbitrary best answer. If the answer stays valid and no worse, the rule is safe.
  3. Check whether a choice changes what is possible later. If a choice uses up a limited budget or changes the remaining problem, as a coin changes the remaining amount, greedy is probably wrong and the problem is a dynamic programming one.

Pitfalls

In the interview

A problem is probably greedy when it asks for a maximum, a minimum or a yes-or-no answer about choosing items under a constraint, and when sorting the input in some natural order seems to settle each decision. Typical signals are phrases such as "the most meetings", "the fewest intervals to remove", "the minimum number of arrows or platforms" and "can you reach the end". Say the rule out loud, say why you believe it is correct, and then code it.

Questions to expect:

  • "How do you know the greedy choice is correct?" Give the exchange argument. Take any best answer, swap the greedy choice into it, and show that it stays valid and no worse. For the booking problem, the first booking of a best schedule can always be replaced by the one that ends earliest.
  • "Why not sort by start time or by duration?" Give a counterexample with three bookings. For start time use 1–10, 2–3 and 4–5, where one long booking blocks two short ones. This shows you tested the alternatives and did not guess.
  • "What if each booking has a payment and you want the most money instead of the most bookings?" Greedy no longer works, because a single large payment can be worth more than several small ones that overlap it. This is weighted interval scheduling, which is solved with dynamic programming over the bookings sorted by end time.
  • "How many rooms are needed to hold all the bookings?" This is a different problem. Sort the bookings by start time and keep a min-heap of the end times of rooms in use. If the earliest-ending room is free when a booking starts, reuse it, and otherwise add a room. The intervals lesson covers it.
  • "What is the fewest number of bookings to cancel so that the rest do not overlap?" Keep as many bookings as possible with the earliest-end rule, and cancel the others. The answer is the total number of bookings minus the number kept. Problems about removing intervals or about the fewest arrows to burst balloons are this same problem in different words.
  • "Which well-known algorithms are greedy?" Kruskal's and Prim's algorithms for minimum spanning trees, Dijkstra's algorithm and Huffman coding are all greedy. Dijkstra's algorithm stops being correct when edge weights can be negative, because a distance that looks final can later be improved, which is the same failure as a greedy choice that is not safe.
  • "How would you return the bookings and not only the count?" Store each kept booking in a list while scanning, instead of incrementing a counter. The time and space stay the same.
  • "What is the complexity?" The time is O(n log n) for the sort and O(n) for the scan. The scan is linear because each decision uses only the end of the last kept booking and never looks back.
  • "When does greedy fail?" When an early choice changes which later choices are available, as in coin change with arbitrary coins and 0/1 knapsack. Name one of these and explain why the exchange argument breaks.
Quick check

Bookings 1–4, 3–5, 4–7, 6–8. Back-to-back is allowed. How many does the earliest-end rule keep?

Coins 1, 5 and 6, amount 10. What does greedy return, and is it the minimum?

Why does the ratio rule work for fractional knapsack but not for 0/1 knapsack?

What to practise next

Intervals builds on the booking problem with merging ranges and counting rooms. For problems where greedy fails, continue to Dynamic Programming.