Huffman Coding
Optimal prefix codes by repeatedly merging the two rarest symbols.
In 1951 David Huffman, a graduate student in Robert Fano's information theory course at MIT, chose a term paper over the final exam and found what the Shannon–Fano method had missed: an optimal prefix code. His algorithm fits in four lines: repeatedly merge the two rarest symbols. Proving that this tiny greedy is optimal is a model exchange argument.
What you’ll learn
- Model prefix codes as binary trees, and use Kraft's inequality to decide which codeword lengths are possible.
- Run Huffman's algorithm and prove it optimal with an exchange lemma and a reduction lemma.
- Implement it in time with a heap, or with two queues when the frequencies are sorted.
- Prove , and explain how block coding, arithmetic coding and ANS get closer to the entropy .
- Explain canonical Huffman codes and length limits, as used in DEFLATE.
Prefix codes are binary trees
A binary code assigns each symbol of an alphabet a bit string, its codeword, of length . The code is a prefix code if no codeword is a prefix of another; then a decoder reads bits until they spell a codeword, outputs its symbol and starts again, with no separators needed.
Prefix codes are exactly binary trees with the symbols at the leaves: a left edge is a 0, a right edge a 1, and a symbol's codeword spells its path from the root, so is its depth. With symbol probabilities (or counts), the expected cost in bits per symbol is
Why. A codeword of length owns the interval of binary fractions that start with , of length ; for a prefix code these intervals are disjoint subsets of , so their lengths sum to at most 1. Conversely, give the codewords in order of increasing length the next free interval of the right size: dyadic intervals laid end to end never overlap.
An optimal tree is full: if an internal node had a single child, contracting that edge would shorten every codeword below it. A full tree satisfies Kraft with equality.
Which list can be the codeword lengths of a binary prefix code?
- 1, 2, 2, 3
- 1, 1, 2
- 2, 2, 2, 2, 2
- 1, 2, 3, 3
Show the answer
D. 1, 2, 3, 3
, so a code exists, for example 0, 10, 110, 111. The other lists have Kraft sums , and : too many short codewords.
Huffman's algorithm, and why it is optimal
Huffman's algorithm (1952): start with one single-leaf tree per symbol, weighted by its frequency. Repeatedly remove the two lightest trees, join them under a new root whose weight is the sum of theirs, and put it back. After merges one tree remains, and it is the code.
Exchange. Let be the two least frequent symbols, and two sibling leaves at the maximum depth of an optimal full tree. Swapping with changes the cost by
since and . Swapping with likewise. So some optimal tree has and as sibling leaves at maximum depth: the greedy-choice property.
Reduction. Replace and by one new symbol with . A tree for the reduced alphabet becomes a tree for the original one by hanging and below the leaf ; since ,
Induction. Removing from gives a reduced tree, so is at least the reduced optimum, which Huffman's remaining merges achieve by induction on . Huffman merges and first, so its cost is the reduced optimum plus :
Four symbols have probabilities 0.4, 0.3, 0.2 and 0.1. What is the expected length of Huffman's code, in bits per symbol?
Show the answer
1.9 bits
Merge 0.1 and 0.2 into 0.3, then the two 0.3s into 0.6, then 0.4 and 0.6. The lengths are 1, 2, 3, 3, so bits, against 2 for a fixed-length code and an entropy of about 1.846 bits.
Building it fast, and the entropy bound
import heapq
from itertools import count
def huffman_code(freq): # freq: {symbol: count}, at least 2 symbols
tie = count() # tie-breaker, so trees are never compared
heap = [(f, next(tie), s) for s, f in freq.items()]
heapq.heapify(heap)
while len(heap) > 1:
f1, _, a = heapq.heappop(heap) # the two lightest trees
f2, _, b = heapq.heappop(heap)
heapq.heappush(heap, (f1 + f2, next(tie), (a, b))) # internal node = pair
code = {}
def walk(node, bits):
if isinstance(node, tuple):
walk(node[0], bits + '0')
walk(node[1], bits + '1')
else:
code[node] = bits
walk(heap[0][2], '')
return codeThe merges cost each, so the tree takes time; writing out the codewords costs their total length. On "rare letters get deeper" it returns codewords of the same lengths as the widget's (ties may be placed differently) and 68 bits in total. Symbols are assumed not to be tuples.
If the frequencies arrive sorted, the heap is unnecessary (van Leeuwen, 1976). When a merge combines the two smallest weights , every other weight is at least , so the next merge produces at least : merged weights come out in nondecreasing order. Keep the leaves in one queue and the merged trees in a second; the two lightest trees are always among the two fronts, and the whole construction takes time.
Lower bound. Let (Kraft–McMillan) and , a probability distribution. Gibbs' inequality says , so
Upper bound. The Shannon lengths satisfy , hence Kraft, so a prefix code with these lengths exists. Huffman is at least as good as that code:
The "+1" can be most of the cost. A source that emits a with probability 0.99 and b with probability 0.01 has entropy about 0.081 bits per symbol, yet every code for single symbols spends at least 1 bit per symbol. Coding blocks of symbols as single super-symbols gives , that is, less than bits per symbol: Huffman on pairs already brings this source down to about 0.515 bits per symbol.
Huffman in practice, and beyond
A decoder needs the code as well as the data. A canonical Huffman code fixes one specific code for given lengths: sort the symbols by (length, symbol), give the first one all zeros, and give each next symbol the previous codeword plus 1, shifted left with appended zeros whenever the length grows. Only the lengths need to be transmitted.
DEFLATE, the format inside zip, gzip and PNG, does exactly this (RFC 1951), and caps codeword lengths at 15 bits. A cap can make Huffman's own tree illegal; the optimal code under a maximum length comes from the package-merge algorithm of Larmore and Hirschberg (1990) in time, though compressors often use simpler heuristic fixes.
| Length | Symbols in order | Canonical codewords |
|---|---|---|
| 2 | e | 00 |
| 3 | ␣ (space), r, t | 010, 011, 100 |
| 4 | a, d, g, l, p, s | 1010, 1011, 1100, 1101, 1110, 1111 |
Huffman is optimal only among codes that spend a whole number of bits on each symbol. Arithmetic coding encodes a whole message as one number in and comes within a couple of bits of the message's information content . Asymmetric numeral systems (ANS; Duda, 2009 and 2013) achieve the same compression at speeds close to Huffman decoding, and a table-based form of ANS is used in the Zstandard compressor.
Key takeaways
- Prefix codes are binary trees with the symbols at the leaves, of cost ; lengths are achievable iff (Kraft, and McMillan for all uniquely decodable codes).
- Huffman merges the two lightest trees times. Optimality: the rarest two can be deepest siblings (exchange), and merging them shifts every cost by exactly (reduction).
- A heap gives time; with sorted frequencies two queues give , because merged weights are produced in nondecreasing order.
- : coding blocks of symbols brings this below per symbol, and arithmetic coding and ANS remove the per-symbol rounding.
- Canonical codes let DEFLATE transmit only the codeword lengths, which it limits to 15 bits; optimal length-limited codes come from package-merge.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why is the tree of an optimal prefix code always full, with every internal node having two children?
- If a node had a single child, contracting that edge would shorten every codeword below it and lower the cost
- Kraft's inequality forbids nodes with one child
- Huffman's algorithm only merges pairs, and only Huffman trees are optimal
- A prefix code must use every bit string of each length
Show the answer
A. If a node had a single child, contracting that edge would shorten every codeword below it and lower the cost
Contracting the edge to a lone child removes one bit from every codeword in that subtree and keeps the code prefix-free, so a tree with a unary node is never optimal (when the probabilities are positive).
A source has entropy bits per symbol. Which of these could be the expected length of its Huffman code?
- 2.0 bits
- 2.35 bits
- 3.3 bits
- 3.4 bits
Show the answer
B. 2.35 bits
Huffman's expected length satisfies , here . Only 2.35 lies in that range.
In the reduction lemma, the two rarest symbols are merged into one symbol with . How do the cost of a tree for the reduced alphabet and the cost of the tree obtained by hanging below relate?
Show the answer
C.
Only and change: each sits one level below 's old position, so together they cost . Every reduced tree maps to a full tree this way at the same extra cost, which is why solving the reduced problem optimally solves the original.
Why does the two-queue implementation build a Huffman tree in time when the frequencies are given in sorted order?
- Sorted frequencies always produce a balanced tree
- It merges equal weights without comparing them
- It needs a heap of size 2 only
- Merged weights come out in nondecreasing order, so both queues stay sorted and the two lightest trees are always at their fronts
Show the answer
D. Merged weights come out in nondecreasing order, so both queues stay sorted and the two lightest trees are always at their fronts
If a merge combines the two smallest weights , every remaining weight is at least , so the next merge creates a weight of at least . Appending merged trees to a second queue therefore keeps it sorted, and each step compares only the queue fronts.
Further reading
- D. A. Huffman, "A method for the construction of minimum-redundancy codes," Proceedings of the IRE 40(9) (1952), 1098–1101.
- T. M. Cover & J. A. Thomas, Elements of Information Theory, 2nd ed. (Wiley, 2006), chapter 5.
- J. van Leeuwen, "On the construction of Huffman trees," Proceedings of the 3rd ICALP (1976), 382–410.
- L. L. Larmore & D. S. Hirschberg, "A fast algorithm for optimal length-limited Huffman codes," Journal of the ACM 37(3) (1990), 464–473.
- P. Deutsch, "DEFLATE Compressed Data Format Specification version 1.3," RFC 1951 (1996).