Sub topic 9
Why the Greedy Choice Is Optimal
Huffman's algorithm never looks ahead. At each step it merges the two lightest nodes in the heap and keeps going. It is fair to ask why such a short-sighted rule should give the best possible code. This chapter proves that it does, explains exactly what "best" covers, and checks the claim with a brute-force search.
This chapter assumes you have read the earlier chapters on prefix-free codes, code trees, and building the Huffman tree with a min-heap. You should also be comfortable with proof by induction.
What "optimal" means here
For a tree T, each symbol s has a frequency f(s) and a leaf depth d(s), and d(s) is also its code length. The cost of the tree is the total number of bits needed to encode the message:
L(T) = sum over symbols of f(s) · d(s)
Dividing by the message length gives the average bits per symbol, so minimizing one minimizes the other. The claim to prove is this:
Among all prefix-free codes that assign one codeword per symbol, given fixed known frequencies, no code has a smaller L(T) than a Huffman code.
The Kraft–McMillan inequality extends this further. Any uniquely decodable code, prefix-free or not, has code lengths that some prefix-free code could also use. So giving up the prefix property never buys a shorter encoding.
A useful identity: cost equals the sum of merges
Every time the algorithm merges two nodes with weights a and b, it creates an internal node of weight a + b. Every leaf below that internal node sits one level deeper because of it. So the tree's cost equals the sum of the weights of all its internal nodes:
L(T) = sum of (a + b) over all merges
The proof below rests on this identity. It also lets you compute Huffman cost without building codes at all.
The proof in three steps
Lemma 1: an optimal tree is full
A full tree is one where every internal node has exactly two children. Suppose an internal node has only one child. Remove that node and move its child up into its place. Every leaf below moves up one level and no other leaf changes, so the cost drops by the total frequency of those leaves. That total is positive, so a tree with a one-child node cannot be optimal.
One consequence matters for the next lemma. In a full tree, the deepest leaf always has a sibling, and that sibling is also a leaf at the same depth.
Lemma 2: the exchange argument
Let x and y be the two least frequent symbols. Some optimal tree has x and y as sibling leaves at the maximum depth.
Start from any optimal tree T. By Lemma 1, it has two sibling leaves a and b at the maximum depth D. Swap x with a. Before the swap, those two leaves contribute f(x)·d(x) + f(a)·D. After the swap, they contribute f(x)·D + f(a)·d(x). The change is:
(after) − (before) = (f(a) − f(x)) · (d(x) − D)
Since x is the rarest symbol, f(a) ≥ f(x), so the first factor is at least zero. Since D is the maximum depth, d(x) ≤ D, so the second factor is at most zero. Their product is at most zero, which means the swap never makes the tree worse. Swap y with b by the same argument. The result is still optimal, and x and y are now deepest siblings.
| Quantity | Before swap | After swap |
|---|---|---|
| Depth of x | d(x) | D |
| Depth of a | D | d(x) |
| Contribution | f(x)·d(x) + f(a)·D | f(x)·D + f(a)·d(x) |
| Change | — | (f(a) − f(x))(d(x) − D) ≤ 0 |
Lemma 3: merging reduces the problem
Take a tree T where x and y are sibling leaves at depth k. Replace their parent with a single leaf z of frequency f(x) + f(y), at depth k − 1. Call the new tree T′, built over an alphabet with one fewer symbol. Then:
L(T) = L(T′) + f(x) + f(y)
The reason is that x and y each contribute one extra bit compared with z. The same relation holds in the other direction. Given any tree for the reduced alphabet, splitting z into two children x and y adds exactly f(x) + f(y).
Putting it together by induction
With two symbols, the only full tree gives each symbol one bit, and that is optimal. Now assume Huffman is optimal for every alphabet with n − 1 symbols, and consider n symbols.
Huffman first merges x and y into z, then builds the optimal tree T′ for the reduced alphabet (by the induction hypothesis), and finally splits z back into x and y to get T. Suppose some tree S had L(S) < L(T). By Lemma 2, we can assume x and y are deepest siblings in S without raising its cost. Collapsing them gives S′ with L(S′) = L(S) − f(x) − f(y) < L(T) − f(x) − f(y) = L(T′). That contradicts the optimality of T′. So T is optimal.
The proof works because the greedy step is safe (Lemma 2) and leaves a smaller problem with the same structure (Lemma 3). Every correct greedy algorithm needs both properties.
Checking the claim by brute force
The code below compares Huffman's cost with an exhaustive search over every set of code lengths that a prefix code could use. Kraft's inequality says a prefix code with lengths l₁, …, lₙ exists exactly when the sum of 2^(−lᵢ) is at most 1. An optimal code never needs a length above n − 1, so the search range is complete.
import heapq
import itertools
import random
from fractions import Fraction
def huffman_cost(freqs):
# Total bits = sum of the weights of all merged (internal) nodes.
heap = list(freqs)
heapq.heapify(heap)
total = 0
while len(heap) > 1:
a = heapq.heappop(heap)
b = heapq.heappop(heap)
total += a + b
heapq.heappush(heap, a + b)
return total
def best_prefix_cost(freqs):
# Try every length assignment that satisfies Kraft's inequality.
n = len(freqs)
best = None
for lengths in itertools.product(range(1, n), repeat=n):
if sum(Fraction(1, 2 ** l) for l in lengths) <= 1:
cost = sum(f * l for f, l in zip(freqs, lengths))
if best is None or cost < best:
best = cost
return best
print(huffman_cost([5, 2, 2, 1, 1])) # abracadabra: 23 bits
random.seed(1)
for _ in range(300):
n = random.randint(2, 6)
freqs = [random.randint(1, 20) for _ in range(n)]
assert huffman_cost(freqs) == best_prefix_cost(freqs), freqs
print("Huffman matched the exhaustive optimum on all trials")For "abracadabra" the cost is 23 bits, or about 2.09 bits per symbol. That is the same figure you got from the encoder in the earlier chapter.
Common errors and gotchas
Optimal does not mean unique
When weights tie, the heap can merge different pairs, and you can end up with differently shaped trees and different code lengths. For frequencies 1, 1, 2, 2, one valid Huffman tree gives lengths (3, 3, 2, 1) and another gives (2, 2, 2, 2). Both cost 12 bits. The proof only promises minimum cost, not one particular tree. Because of this, the decoder cannot just rerun the algorithm and hope for the same tree. The canonical Huffman chapter addresses this problem.
Top-down splitting is not the same algorithm
Shannon–Fano coding also uses frequencies, but it works top-down. It splits the symbols into two groups of nearly equal weight and recurses. That approach feels just as reasonable, but it is not optimal. For frequencies 15, 7, 6, 6, 5, Shannon–Fano produces lengths 2, 2, 2, 3, 3 for a cost of 89 bits. Huffman gives lengths 1, 3, 3, 3, 3 for a cost of 87 bits. The bottom-up merge is what makes the exchange argument go through.
The objective is weighted length, not maximum length
Huffman minimizes total bits. It does nothing to limit the longest codeword, which can grow to n − 1 bits when frequencies are very skewed, such as Fibonacci-like weights. Formats with a cap on code length need a different algorithm. The length-limited codes chapter covers that.
Frequencies must match the data
The proof assumes the frequencies used to build the tree are the true frequencies of the message being coded. If you build a tree from one sample and use it on different data, the optimality guarantee is lost.
Exercise
In a tree, symbol x has frequency 2 at depth 1, and symbol a has frequency 9 at depth 4 (the maximum depth). By how many bits does swapping x and a change the cost, and in which direction?
Show answer
The change is (f(a) − f(x))(d(x) − D) = (9 − 2)(1 − 4) = −21. The swap saves 21 bits. This shows the original tree was not optimal, because a rare symbol sat higher in the tree than a common one.
Exercise
Compute the Huffman cost for frequencies 1, 1, 2, 4 using the sum-of-merges identity, then confirm it from the code lengths.
Show answer
The merges are 1+1=2, then 2+2=4, then 4+4=8, so the cost is 2+4+8 = 14. The code lengths are 3, 3, 2, 1, which gives 1·3 + 1·3 + 2·2 + 4·1 = 14.
Exercise
Why does Lemma 2 need Lemma 1 first?
Show answer
The exchange argument needs two sibling leaves at the maximum depth to swap x and y into. Only in a full tree is the deepest leaf guaranteed to have a sibling that is also a leaf. Lemma 1 shows that every optimal tree is full, so those two leaves always exist.