Sub topic 11
Huffman Coding: Optimal Prefix Codes
This chapter assumes you know Python's heapq module, binary trees, and the exchange argument covered earlier in this tutorial.
The Problem
Suppose you need to compress a file. A fixed-length code gives every symbol the same number of bits, so six symbols need 3 bits each. If some symbols appear far more often than others, you save space by giving frequent symbols short codewords and rare symbols long ones.
Variable-length codes only work if decoding is unambiguous. A prefix code guarantees this because no codeword is a prefix of another. Any prefix code is a binary tree. Each symbol sits at a leaf, a left edge means 0, and a right edge means 1. The cost of the tree is the sum of freq(s) × depth(s) over all symbols. Huffman's algorithm finds a tree with the minimum cost.
The Greedy Rule
Huffman's rule is to repeatedly merge the two least frequent subtrees into a new subtree whose frequency is their sum. Stop when one tree remains.
import heapq
from itertools import count
def huffman_codes(freqs):
tie = count()
heap = [(f, next(tie), sym) for sym, f in freqs.items()]
heapq.heapify(heap)
if len(heap) == 1:
return {heap[0][2]: "0"}
while len(heap) > 1:
f1, _, left = heapq.heappop(heap)
f2, _, right = heapq.heappop(heap)
heapq.heappush(heap, (f1 + f2, next(tie), (left, right)))
codes = {}
def walk(node, prefix):
if isinstance(node, tuple):
walk(node[0], prefix + "0")
walk(node[1], prefix + "1")
else:
codes[node] = prefix
walk(heap[0][2], "")
return codes
print(huffman_codes({"a": 45, "b": 13, "c": 12, "d": 16, "e": 9, "f": 5}))
# {'a': '0', 'c': '100', 'b': '101', 'f': '1100', 'e': '1101', 'd': '111'}The merges happen in this order: f+e=14, c+b=25, 14+d=30, 25+30=55, a+55=100. The total cost is 45·1 + 12·3 + 13·3 + 5·4 + 9·4 + 16·3 = 224 bits. A fixed 3-bit code would cost 300 bits.
Each heap operation costs O(log n), and there are n − 1 merges, so the algorithm runs in O(n log n).
Why It Is Optimal
The proof has two steps, and each matches a property from earlier chapters.
- Greedy choice (exchange argument). Let x and y be the two least frequent symbols. Take any optimal tree and find two sibling leaves at its deepest level. Swap x and y into those positions. Moving a lower-frequency symbol deeper never increases the cost, so some optimal tree has x and y as deepest siblings.
- Optimal substructure. Replace x and y with one new symbol z where
freq(z) = freq(x) + freq(y). If T′ is a tree for the smaller alphabet, expanding z back into x and y gives a tree T withcost(T) = cost(T′) + freq(x) + freq(y). The added term is a constant, so an optimal T′ produces an optimal T. Induction on the alphabet size completes the proof.
Exercise
For frequencies A=5, B=2, C=1, D=1, give the Huffman code length for each symbol and the total encoded size in bits. Compare it with a fixed-length code.
Show answer
Merge C+D=2, then B+2=4, then 4+A=9. The lengths are A=1, B=2, C=3, D=3. The total is 5·1 + 2·2 + 1·3 + 1·3 = 15 bits. A fixed 2-bit code needs 9·2 = 18 bits.
Exercise
What goes wrong if you remove the counter and push (frequency, subtree) pairs onto the heap?
Show answer
When two entries have equal frequency, Python compares their second elements. That can mean comparing a string with a tuple, which raises a TypeError. Even when the comparison succeeds, the heap ends up comparing whole subtrees for no reason. The counter gives each entry a unique second key, so the heap never compares subtrees.