Why Huffman Codes Are Optimal
Huffman's algorithm makes one greedy decision over and over: join the two lightest trees. The previous lesson showed that it produces short codes. This lesson proves that no prefix code is shorter, using exactly the two-property recipe of The Greedy-Choice Property and Exchange Arguments: an exchange argument for the greedy choice and a cost identity for optimal substructure. Then it checks the theorem by brute force on random inputs and ends with a linear-time version of the algorithm.
Throughout, is the alphabet with frequencies , a full binary tree whose leaves are the symbols, and its cost.
Lemma 1: the greedy choice is safe
Lemma 1. Let and be two symbols of lowest frequency. Then some optimal tree has and as sibling leaves at the maximum depth, so their codewords have the same length and differ only in the last bit.
Proof. Take any optimal tree . Being full, it has two sibling leaves and at its maximum depth (the deepest leaf's parent has two children, and both must be leaves). Name them so that , and name so that . Since and are the two least frequent symbols, and .
Swap and in the tree, giving . Only those two leaves change depth, so
because both factors are non-negative: is at least as frequent as and at maximum depth. So . Swap and the same way to get with . Since was optimal, is optimal too, and in it and are siblings at maximum depth. (If or already coincides with or , some swaps are unnecessary; the inequalities still hold.)
The swap is the whole idea: moving a rarer symbol deeper and a more common one shallower never hurts. It is the rearrangement inequality applied to depths and frequencies.
Lemma 2: optimal substructure
Let be two least frequent symbols. Form the alphabet with a new symbol , . This is exactly what one Huffman merge does.
Lemma 2. If is an optimal tree for , then the tree obtained from by replacing the leaf with an internal node whose children are and is optimal for .
Proof. First the cost relation. Every symbol other than has the same depth in and , and . So
Now suppose were not optimal: some tree for has . By Lemma 1 we may assume and are siblings in . Replace them and their parent by a single leaf , giving a tree for with , which contradicts the optimality of .
The theorem
Theorem. Huffman's algorithm produces an optimal prefix code.
Proof by induction on . For the only full tree has both symbols at depth 1, and Huffman produces it. For , the algorithm's first step merges two least frequent symbols into , and the remaining steps are exactly Huffman's algorithm on , which has symbols. By induction they build an optimal tree for , and by Lemma 2, expanding into and gives an optimal tree for .
Lemma 1 is the greedy-choice property and Lemma 2 the optimal substructure. Notice how Lemma 2 uses Lemma 1 inside its proof: optimal substructure for a greedy algorithm is about the subproblem that remains after the greedy choice, so the competitor must first be brought into a form that makes the same choice.
Checking by brute force
To test the theorem independently of the proof, compute the optimum by brute force. A full binary tree with leaves corresponds to a multiset of leaf depths satisfying the Kraft equality , and every such multiset is realised by some full tree. Given the depths, the best assignment of symbols puts the most frequent symbols at the smallest depths (the swap of Lemma 1 again). So the optimum is a minimum over depth multisets, which is small enough to enumerate for .
import heapq, random
from itertools import combinations_with_replacement
def huffman_cost(freqs):
if len(freqs) == 1:
return freqs[0]
h = list(freqs); heapq.heapify(h); total = 0
while len(h) > 1:
a = heapq.heappop(h); b = heapq.heappop(h)
total += a + b
heapq.heappush(h, a + b)
return total
def brute_force_cost(freqs):
n = len(freqs)
best = None
for depths in combinations_with_replacement(range(1, n), n): # sorted depth multisets
if sum(1 << (n - 1 - d) for d in depths) == 1 << (n - 1): # Kraft sum 1: a full binary tree
cost = sum(f * d for f, d in zip(sorted(freqs, reverse=True), depths))
best = cost if best is None else min(best, cost)
return best
print("example:", huffman_cost([21, 9, 16, 4, 30, 8, 12]), brute_force_cost([21, 9, 16, 4, 30, 8, 12]))
rng = random.Random(12)
ok, tested = True, 0
for _ in range(100):
freqs = [rng.randint(1, 50) for _ in range(rng.randint(2, 7))]
ok &= huffman_cost(freqs) == brute_force_cost(freqs)
tested += 1
print(f"Huffman equals the brute-force optimum on {tested} random alphabets:", ok)example: 261 261
Huffman equals the brute-force optimum on 100 random alphabets: True
The exchange, numerically
The program builds a deliberately bad code for the example alphabet, then applies the swaps of Lemma 1 one at a time and prints the cost after each.
freq = {"A": 21, "B": 9, "C": 16, "D": 4, "E": 30, "F": 8, "G": 12}
# a valid full-tree depth assignment (Kraft sum 1), but with the symbols placed badly
depth = {"E": 4, "A": 4, "C": 4, "G": 4, "B": 2, "F": 2, "D": 2}
assert sum(2 ** -d for d in depth.values()) == 1
def cost(depth):
return sum(freq[s] * depth[s] for s in freq)
print("bad placement:", cost(depth))
changed = True
while changed: # swap any pair where the rarer symbol is shallower
changed = False
for a in freq:
for b in freq:
if freq[a] < freq[b] and depth[a] < depth[b]:
gain = (freq[b] - freq[a]) * (depth[b] - depth[a])
depth[a], depth[b] = depth[b], depth[a]
print(f"swap {a} (freq {freq[a]}) and {b} (freq {freq[b]}): saves {gain:3}, cost now {cost(depth)}")
changed = True
print("final depths:", dict(sorted(depth.items())))bad placement: 358
swap B (freq 9) and A (freq 21): saves 24, cost now 334
swap D (freq 4) and B (freq 9): saves 10, cost now 324
swap F (freq 8) and C (freq 16): saves 16, cost now 308
swap A (freq 21) and E (freq 30): saves 18, cost now 290
swap B (freq 9) and A (freq 21): saves 24, cost now 266
final depths: {'A': 2, 'B': 4, 'C': 2, 'D': 4, 'E': 2, 'F': 4, 'G': 4}
Each swap saves exactly bits, the product in Lemma 1. When no swap helps, the depths are sorted against the frequencies, the best this tree shape allows. The result is 266, still worse than Huffman's 261: swaps only reassign symbols to leaves, while Huffman also chooses the shape (leaf depths instead of this tree's ).
A linear-time variant
If the frequencies come sorted, the priority queue can be replaced by two plain queues: one holding the original symbols in increasing order, one receiving the merged trees. Merged weights are produced in non-decreasing order (each merge takes the two smallest available weights, and they never decrease), so the second queue stays sorted automatically, and the two smallest items are always at the fronts of the two queues. Every step is , so the algorithm is after sorting.
In C++
#include <algorithm>
#include <cstdio>
#include <deque>
#include <vector>
long long huffman_two_queues(std::vector<long long> freqs) {
std::sort(freqs.begin(), freqs.end());
if (freqs.size() == 1) return freqs[0];
std::deque<long long> leaves(freqs.begin(), freqs.end()), merged;
auto pop_min = [&]() {
std::deque<long long>& q = merged.empty() || (!leaves.empty() && leaves.front() <= merged.front()) ? leaves : merged;
long long x = q.front();
q.pop_front();
return x;
};
long long total = 0;
for (size_t k = 1; k < freqs.size(); ++k) {
long long x = pop_min(), y = pop_min();
total += x + y;
merged.push_back(x + y); // non-decreasing, so this queue stays sorted
}
return total;
}
int main() {
std::printf("%lld\n", huffman_two_queues({21, 9, 16, 4, 30, 8, 12}));
std::printf("%lld\n", huffman_two_queues({1, 2, 4, 8, 16, 32}));
std::vector<long long> many;
for (int i = 1; i <= 100000; ++i) many.push_back(1 + (1LL * i * i) % 1000);
std::printf("%lld\n", huffman_two_queues(many));
}261
119
753801119
Test yourself
In Lemma 1, swapping a least frequent symbol with a deepest leaf changes the cost by . Why is this never positive?
- Because is always at the root
- Because and , so the product is non-negative
- Because the tree is balanced
- Because frequencies are integers
If merging and into gives the tree for the reduced alphabet, what is for the expanded tree?
Which depth multisets can be the leaf depths of a full binary tree with four leaves?
- and