Sub topic 11
Huffman Coding: Optimal Prefix Codes
This chapter assumes you can work with Python dictionaries and heapq, that you know what a binary tree is, and that you have read the earlier chapters on the exchange argument and optimal substructure. The Huffman correctness proof uses both of those ideas.
The problem: compress text with variable-length codes
Suppose a file contains only the six symbols a through f. A fixed-length code needs 3 bits per symbol, because 2 bits cover only 4 symbols. If some symbols are much more common than others, you can save space by giving frequent symbols short codewords and rare symbols long ones.
Variable-length codes cause a decoding problem. If a = 0 and b = 01, a bit string that starts with 0 could be either symbol. A prefix code removes the ambiguity. In a prefix code, no codeword is a prefix of another codeword. The decoder reads bits until they match a codeword, outputs that symbol, and starts again, and it never needs to look ahead.
Each prefix code corresponds to a binary tree. Symbols sit at the leaves. A left edge stands for 0 and a right edge for 1. A symbol's codeword is the path from the root to its leaf, so the codeword length equals the leaf's depth. With frequencies f(c), the cost of a tree T is:
B(T) = sum over symbols c of f(c) × depth_T(c)
The goal is a tree that minimizes B(T).
| Symbol | Frequency (thousands) | Fixed code | Huffman code |
|---|---|---|---|
| a | 45 | 000 | 0 |
| b | 13 | 001 | 101 |
| c | 12 | 010 | 100 |
| d | 16 | 011 | 111 |
| e | 9 | 100 | 1101 |
| f | 5 | 101 | 1100 |
The fixed code costs 100 × 3 = 300 thousand bits. The Huffman code costs 45·1 + 13·3 + 12·3 + 16·3 + 9·4 + 5·4 = 224 thousand bits, which is about 25% smaller.
The greedy rule: merge the two rarest
Huffman's algorithm builds the tree from the bottom up:
- Make every symbol a one-node tree whose weight is its frequency.
- Remove the two trees with the smallest weights.
- Join them under a new parent whose weight is the sum of the two weights, and put that tree back.
- Repeat until one tree is left.
At each step the greedy choice is "the two rarest things go deepest," and the algorithm never revisits that choice. A min-heap makes each "find the two smallest" step cost O(log n).
The merge order for this input is: f+e = 14, c+b = 25, 14+d = 30, 25+30 = 55, a+55 = 100.
Implementation
The code below builds the codes, then encodes and decodes a string to show the round trip. The counter tie matters. Without it, two heap entries with equal weight would make Python compare the third tuple element, which might be a string against a tuple, and that raises TypeError.
import heapq
from collections import Counter
from itertools import count
def huffman_codes(freqs):
if not freqs:
return {}
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
def encode(text, codes):
return "".join(codes[ch] for ch in text)
def decode(bits, codes):
lookup = {code: sym for sym, code in codes.items()}
out, buf = [], ""
for bit in bits:
buf += bit
if buf in lookup: # safe because no codeword is a prefix of another
out.append(lookup[buf])
buf = ""
return "".join(out)
freqs = {"a": 45, "b": 13, "c": 12, "d": 16, "e": 9, "f": 5}
codes = huffman_codes(freqs)
print(codes)
# {'a': '0', 'c': '100', 'b': '101', 'f': '1100', 'e': '1101', 'd': '111'}
print(sum(freqs[s] * len(c) for s, c in codes.items())) # 224
text = "abacabadfe"
codes = huffman_codes(Counter(text))
bits = encode(text, codes)
print(bits, decode(bits, codes) == text)The input dictionary must not use tuples as symbols, because walk treats any tuple as an internal node. If your symbols could be tuples, wrap internal nodes in a small class instead.
Why the greedy choice is safe: the exchange argument
The proof has two lemmas. One gives the greedy choice property and the other gives optimal substructure.
Lemma 1: the two rarest symbols can be deepest siblings
Let x and y be the two lowest-frequency symbols. First, every optimal tree is full, meaning every internal node has two children. If a node had only one child, you could replace the node with that child, which shortens every codeword below it and lowers the cost. So in an optimal tree T, the deepest leaf has a sibling leaf. Call the pair a and b.
Now swap x with a. Since f(x) ≤ f(a) and depth(x) ≤ depth(a), the change in cost is:
(f(x) − f(a)) × (depth(a) − depth(x)) ≤ 0
The cost does not go up. Swap y with b in the same way. The result is still optimal, and in it x and y are sibling leaves at maximum depth. Making the greedy merge first therefore never rules out an optimal answer.
Lemma 2: the merged problem has the same shape
Replace x and y with a new symbol z where f(z) = f(x) + f(y). Take any tree T′ for the reduced alphabet, and expand the leaf z into an internal node whose children are x and y. Call the expanded tree T. Then x and y sit one level deeper than z did, so:
B(T) = B(T′) + f(x) + f(y)
The extra term f(x) + f(y) is a constant that does not depend on T′. Minimizing B(T′) therefore minimizes B(T). Suppose some better tree for the original alphabet existed. By Lemma 1 it could be rearranged so that x and y are siblings, and collapsing them would give a reduced tree cheaper than T′, which contradicts T′ being optimal. Induction on the alphabet size finishes the proof.
Edge cases and gotchas
Ties produce different but equally good codes
When weights tie, the heap's tie-breaking decides which trees merge first. Different choices can produce different codeword lengths, not just different bit labels, and every one of them has the same minimum cost. Do not write tests that expect specific codewords. Test the cost and the encode-decode round trip instead.
The decoder needs the tree
The decoder must rebuild exactly the encoder's code. Real formats such as DEFLATE use canonical Huffman codes. They transmit only the codeword lengths, and both sides assign codewords in a fixed order: sorted by length, then by symbol. This keeps the header small and avoids any dependence on tie-breaking.
Complexity
There are n − 1 merges, and each one does a constant number of heap operations, so the total is O(n log n). If the frequencies arrive already sorted, a two-queue method reaches O(n). Keep the sorted leaves in one queue and the merged trees in a second queue. Merged weights come out in non-decreasing order, so the two smallest items are always at the fronts of the two queues.
What "optimal" does and does not mean
Huffman coding is optimal among prefix codes that assign each symbol a whole number of bits and use a fixed frequency table. It is not optimal for compression in general. Arithmetic coding can spend a fraction of a bit per symbol, which matters when one symbol has a probability close to 1. Huffman also ignores context. For example, u is very likely to follow q, and a Huffman code built from overall symbol counts cannot use that.
| Situation | Huffman behavior |
|---|---|
| One symbol | Assign "0", or store the count only |
| All frequencies equal, n = 2^k | Gives a fixed-length k-bit code |
| One symbol has probability near 1 | Still uses at least 1 bit for it, which wastes space compared with arithmetic coding |
| Frequencies change over time | Static code becomes stale; use adaptive Huffman or rebuild per block |
Exercise
Build a Huffman code for frequencies a:1, b:1, c:2, d:3, e:5. What is the total cost, and what codeword length does each symbol get?
Show answer
The merges are a+b = 2, then 2+c = 4, then d+4 = 7, then e+7 = 12. The cost is the sum of the merged weights: 2 + 4 + 7 + 12 = 25. The lengths are e = 1, d = 2, c = 3, a = 4, b = 4. Check: 5·1 + 3·2 + 2·3 + 1·4 + 1·4 = 25.
Exercise
For frequencies a:1, b:1, c:2, d:2, show two Huffman trees with different codeword lengths and prove they cost the same.
Show answer
First merge a+b = 2. Three trees of weight 2 remain. If you merge c+d next, then (ab)+(cd), every symbol gets length 2, and the cost is 6 × 2 = 12. If you merge (ab)+c next, then that tree with d, the lengths are d = 1, c = 2, a = 3, b = 3, and the cost is 2·1 + 2·2 + 1·3 + 1·3 = 12. Both choices are valid tie-breaks and both are optimal.
Exercise
Lemma 1 relies on the fact that an optimal prefix-code tree is full. Explain why a tree with an internal node that has only one child cannot be optimal, assuming all frequencies are positive.
Show answer
Remove that internal node and attach its only child directly to the node's parent. If the node is the root, the child becomes the root. Every leaf in that subtree moves up one level, so its codeword gets one bit shorter. The code is still a prefix code, and the cost drops by the total frequency of those leaves, which is positive. So the original tree was not optimal.