Huffman Codes: Construction, Optimality, and the Redundancy Bound
Anchor (Master): Cover & Thomas 2006 Elements of Information Theory 2e (Wiley) §5.1-5.5; Gallager 1978 Variations on a Theme by Huffman IEEE Trans. Info. Theory 24(6) 668-674; Capocelli et al. 1991 On the Redundancy of Huffman Codes IEEE Trans. Info. Theory 37(1) 144-148
Intuition Beginner
Imagine you are packing a suitcase. You use small containers for things you bring rarely and large containers for things you bring often. The Huffman algorithm does this for data: it assigns short codewords to frequent symbols and long codewords to rare ones.
Start with every symbol as its own node, each labelled with its probability. Find the two nodes with the smallest probabilities and merge them into a parent node whose probability is their sum. Repeat until one node remains. The resulting binary tree is the Huffman tree. Reading the left/right branches as 0/1 gives the codewords.
Why is this good? Because the algorithm is greedy but optimal. At every step, the two least probable symbols are siblings in the tree. This guarantees that no other prefix-free code can have a shorter expected length. The proof works by an exchange argument: if any optimal code had those two symbols far apart, you could swap them with deeper nodes and shorten the code, contradicting optimality.
The redundancy bound says the expected length of a Huffman code exceeds the entropy by less than one bit, and in fact by less than bits, where is the largest symbol probability. For a uniform source with many symbols, is small and the code is nearly optimal.
Visual Beginner
Figure: a Huffman tree for the source with probabilities . The two least-probable symbols (0.10) and (0.10) merge first into a node of weight 0.20. This node merges with (0.20) and (0.20) in subsequent steps. The final tree assigns: , , , , .
| Symbol | Probability | Codeword | Length | Contribution to |
|---|---|---|---|---|
| a | 0.40 | 0 | 1 | 0.40 |
| b | 0.20 | 10 | 2 | 0.40 |
| c | 0.20 | 110 | 3 | 0.60 |
| d | 0.10 | 1110 | 4 | 0.40 |
| e | 0.10 | 1111 | 4 | 0.40 |
Expected length: bits. The entropy is bits. The redundancy is bits.
Worked example Beginner
Consider English letter frequencies (approximate, top 8 letters plus a catch-all). The probabilities are:
- E: 0.13, T: 0.09, A: 0.08, O: 0.08, I: 0.07, N: 0.07, S: 0.06, H: 0.06, other: 0.36.
Step 1. Place all nine symbols in a list with their probabilities.
Step 2. Merge the two smallest: S (0.06) and H (0.06) become a node of weight 0.12.
Step 3. Merge the next two smallest: I (0.07) and N (0.07) become weight 0.14.
Step 4. Now the list is: E (0.13), {S,H} (0.12), T (0.09), A (0.08), O (0.08), {I,N} (0.14), other (0.36). Merge A and O: weight 0.16.
Step 5. Merge T (0.09) and {S,H} (0.12): weight 0.21.
Step 6. Merge E (0.13) and {I,N} (0.14): weight 0.27.
Continue until one node remains. The expected codeword length is approximately 2.84 bits per letter. The entropy of this distribution is approximately 2.79 bits. The redundancy is about 0.05 bits, well within the bound.
Compare this with a fixed-length code. With 9 symbols, a fixed-length code needs 4 bits per symbol (since ). The Huffman code saves about 1.16 bits per symbol, a 29% reduction. Over a million characters of English text, the Huffman code would save roughly 1.16 million bits, or about 145 kilobytes. This is why Huffman coding is the backbone of file compression.
Check your understanding Beginner
Formal definition Intermediate+
Let be a finite source alphabet with probability distribution where and .
Definition (Prefix-free code). A code is prefix-free if no codeword is a prefix of another. The set of codewords forms a prefix-free set.
Definition (Expected length). The expected length of a code for source is
where is the length of the codeword for .
Definition (Huffman code). The Huffman code is constructed by the following algorithm:
- Create a leaf node for each symbol with weight .
- While more than one node remains: a. Select the two nodes with the smallest weights. b. Create a new internal node with weight equal to the sum of the two selected nodes' weights. c. Make the two selected nodes children of the new node (assign 0 to one branch, 1 to the other).
- The remaining node is the root of the Huffman tree.
The codeword for each symbol is the sequence of branch labels on the path from root to leaf.
Counterexamples to common slips
The Huffman code is not unique. Different tie-breaking rules produce different trees with different codeword assignments. All such codes have the same expected length (which is optimal).
Optimality is within the class of prefix-free codes. The Huffman code minimises over all prefix-free codes. It does not minimise over all uniquely decodable codes, but by Kraft's inequality the minimum expected length is the same for both classes.
The bound holds for any distribution, but the tighter bound involves . For a highly skewed distribution with , the redundancy can be close to zero; for a near-uniform distribution, it is also close to zero. The worst case is in between.
Key theorem with proof Intermediate+
Theorem (Optimality of Huffman codes). For any discrete source with distribution , the Huffman code achieves the minimum expected codeword length among all prefix-free codes.
Proof. The proof proceeds by induction on using an exchange argument.
Base case (). With two symbols, the Huffman code assigns 0 and 1, giving expected length 1. Any prefix-free code for two symbols must have at least one codeword of length 1, and the only such code has expected length 1. So the Huffman code is optimal.
Inductive step. Assume optimality holds for all sources with symbols. Let be a distribution on symbols, and assume (by relabelling) that . Let be any optimal prefix-free code for with codeword lengths .
Claim: In , the two symbols with the smallest probabilities ( and ) can be assumed to be siblings (i.e., their codewords differ only in the last bit, and ).
Proof of claim: If , swap the codeword of with that of any symbol at depth . Since and the swap shortens the codeword of while lengthening the codeword of a higher-probability symbol, the expected length decreases or stays the same. Similarly, if is not a sibling of but has some other symbol as a sibling at the same depth, swap and (which does not change expected length since and they are at the same depth). Hence we may assume and are siblings.
Now merge and into a single meta-symbol with probability . This creates a source with symbols. By the induction hypothesis, the Huffman code for this reduced source is optimal. The Huffman code for the original source is obtained by expanding back into and (appending 0 and 1 respectively), which adds exactly to the expected length. Any optimal code for the original source must also have and as siblings (by the claim), so it similarly corresponds to a code for the reduced source. By the induction hypothesis, no code for the reduced source has shorter expected length than the Huffman code. Therefore no code for the original source has shorter expected length than the Huffman code.
Bridge. The optimality of Huffman codes builds toward the method of types in 46.02.06, where universal codes operate without knowing the source distribution and the redundancy bound here quantifies the price of ignorance. This is exactly the starting point for universal source coding, where the redundancy over entropy becomes the overhead of learning the distribution from data. The exchange argument appears again in 46.03.03 as the structural backbone of Fano's inequality, and the foundational reason entropy governs compression is that the Huffman redundancy vanishes as the alphabet grows. The central insight is that greedy local merging produces a globally optimal code, generalises to -ary alphabets for non-binary channels, and is dual to the sphere-packing argument in 46.03.04 where the geometric structure of codewords determines capacity.
Exercises Intermediate+
Lean formalization Intermediate+
Mathlib does not define prefix-free codes or the Huffman algorithm. The ComputeQuantities and Omega frameworks for computational reasoning are available, but there is no PrefixFreeCode type, no expected-length functional, and no optimality theorem. A Codex.InformationTheory.Huffman module would need to define a binary tree type for code trees, a prefix-free predicate, an expected-length functional, the merge algorithm, and the optimality proof by induction and exchange. The redundancy bound requires additional analysis of the Shannon code as an intermediate step. This unit ships without formal verification.
Advanced results Master
The sibling property and code characterisation
Gallager (1978) introduced the sibling property: a binary prefix code on symbols is a Huffman code if and only if the corresponding code tree has the property that its nodes (internal nodes and leaves combined) can be listed in order of non-increasing probability so that each pair of siblings is adjacent in the list.
This characterisation provides an efficient test for whether a given prefix-free code is a Huffman code without re-running the algorithm: compute the node probabilities and check the sibling property. It also gives a clean proof that the Huffman code is optimal, since any non-Huffman code violates the sibling property, and the violation identifies a local swap that reduces expected length.
The Shannon code and its competitive optimality
The Shannon code assigns length to symbol . By construction, . The Huffman code satisfies , so .
Cover and Thomas (2006, §5.5) prove a stronger result: the Shannon code is competitively optimal in the sense that for any other prefix-free code with lengths ,
The Huffman code inherits this property. This means the Huffman code is not just optimal on average but also dominates any competitor symbol-by-symbol in a probabilistic sense.
Tight redundancy bounds
The general redundancy bound is , due to Gallager (1978). A sharper result by Capocelli, De Santis, and Gargano (1991) shows:
where and is the binary entropy. For the special case , the bound simplifies to .
The redundancy is zero exactly when the distribution is dyadic (all probabilities are negative powers of 2). This is the only case where the Shannon code lengths are all integers, and the Huffman code achieves exact entropy.
Adaptive and canonical Huffman codes
In practice, the source distribution is often unknown. Adaptive Huffman coding (the FGK algorithm of Faller, Gallager, and Knuth) updates the Huffman tree incrementally as symbols are observed, maintaining the sibling property at each step. The redundancy of adaptive Huffman coding over a stationary source converges to the static redundancy as .
Canonical Huffman codes assign codewords in a fixed order (e.g., the first codeword of length is the binary increment of the last codeword of length ), which allows compact representation of the codebook: only the codeword lengths need to be transmitted, and the decoder reconstructs the canonical code from these lengths.
Synthesis. The Huffman algorithm is the unique greedy procedure that produces an optimal prefix-free code; the exchange argument at its core builds toward the method of types in 46.02.06 where universal codes achieve entropy without knowing the distribution. The redundancy bound quantifies the gap between practice and theory, and the sibling property characterises Huffman codes structurally. The central insight is that local greedy merging guarantees global optimality, generalises to -ary alphabets and adaptive settings, and is dual to the Kraft inequality that constrains all prefix-free codes. Putting these together, the Huffman code is not merely a good heuristic but an exact solution to the optimal coding problem, with the redundancy bound characterising how far any practical code can deviate from the entropy limit.
Full proof set Master
Proposition (Redundancy bound via Shannon code). Let be the Huffman code and be the Shannon code for distribution . Then .
Proof. The Shannon code assigns lengths . Since , we have for each . Summing: .
Since the Huffman code minimises expected length over all prefix-free codes, .
Proposition (Huffman redundancy for dyadic distributions). If the distribution is dyadic (each for positive integers ), then .
Proof. For a dyadic distribution, the Kraft sum with is , so by Kraft's theorem there exists a prefix-free code with these lengths. The expected length is . Since for any code (by the noiseless coding theorem, which follows from via Kraft's inequality and the log-sum inequality), this code achieves the lower bound. The Huffman code, being optimal, must also achieve .
Connections Master
46.02.02— Shannon's source coding theorem establishes as the compression limit; the Huffman code achieves this limit up to the redundancy bound.46.02.01— The AEP shows that the typical set has elements; Huffman coding assigns bits per symbol, matching the AEP rate.46.02.06— The method of types and universal coding extend Huffman coding to settings where the source distribution is unknown; the redundancy bound quantifies the overhead.46.03.04— Sphere-packing bounds for channel codes are the dual of prefix-free constraints for source codes; both are governed by counting arguments.40.06.06— Linear codes and the Gilbert-Varshamov bound share the combinatorial counting structure that underlies the Kraft inequality.
Historical & philosophical context Master
David Huffman was a graduate student at MIT when he invented the algorithm in 1951. His information theory professor, Robert Fano, assigned the class a term paper on optimal prefix-free codes. Huffman, unable to prove anything about the existing top-down approach (Shannon-Fano coding), discarded it and invented the bottom-up merge algorithm in a flash of insight. The result was published in the Proceedings of the IRE in 1952 as "A Method for the Construction of Minimum-Redundancy Codes" (40(9), pp. 1098-1101). Fano is said to have remarked that Huffman had solved the problem that Fano and Shannon had both failed to crack.
The algorithm became one of the most widely deployed compression techniques in computing. It forms the backbone of JPEG image compression (after DCT and quantisation), MP3 audio compression, and the DEFLATE algorithm used in gzip and PNG. Canonical Huffman codes were adopted by the deflate format to minimise header overhead.
Robert Gallager's 1978 paper "Variations on a Theme by Huffman" (IEEE Trans. Info. Theory 24(6), pp. 668-674) deepened the theoretical understanding by introducing the sibling property and proving the tighter redundancy bounds. The adaptive FGK algorithm (Faller 1973, Gallager 1978, Knuth 1985) extended Huffman coding to the online setting where the source distribution is learned on the fly.
Bibliography Master
@article{huffman1952,
author = {Huffman, D. A.},
title = {A Method for the Construction of Minimum-Redundancy Codes},
journal = {Proceedings of the IRE},
volume = {40},
number = {9},
pages = {1098--1101},
year = {1952},
}
@article{gallager1978,
author = {Gallager, R. G.},
title = {Variations on a Theme by {Huffman}},
journal = {IEEE Transactions on Information Theory},
volume = {24},
number = {6},
pages = {668--674},
year = {1978},
}
@article{capocelli1991,
author = {Capocelli, R. M. and De Santis, A. and Gargano, L.},
title = {On the Redundancy of {Huffman} Codes},
journal = {IEEE Transactions on Information Theory},
volume = {37},
number = {1},
pages = {144--148},
year = {1991},
}
@book{cover-thomas2006,
author = {Cover, T. M. and Thomas, J. A.},
title = {Elements of Information Theory},
edition = {2nd},
publisher = {Wiley},
year = {2006},
}
@article{knuth1985,
author = {Knuth, D. E.},
title = {Dynamic {Huffman} Coding},
journal = {Journal of Algorithms},
volume = {6},
pages = {163--180},
year = {1985},
}