Contents / Information Theory / Huffman and Shannon–Fano Codes
Chapter 5
Huffman and Shannon–Fano Codes
Building an optimal prefix code symbol by symbol, proving it optimal, and seeing where the older Shannon–Fano construction falls short.
Introduction
Building an optimal prefix code symbol by symbol, proving it optimal, and seeing where the older Shannon–Fano construction falls short.
5.1Huffman's Algorithm
Kraft's inequality tells us which length vectors are legal; the Shannon code shows that a legal vector within one bit of the entropy always exists. It does not tell us the best legal vector. That problem — minimise over all prefix codes — was solved in 1952 by David Huffman. The algorithm is three lines long, runs in time, and is provably optimal.
The idea is to build the code tree from the leaves upward. The two rarest symbols will end up deepest in the tree, so we decide their relationship first and then forget that they were ever separate.
Method 5.1 (Huffman's algorithm). Input: probabilities over the symbols of .
- Create one leaf node per symbol, weighted by its probability, and place all nodes in a priority queue.
- While more than one node remains: remove the two nodes of smallest weight, create a new internal node whose weight is their sum, and attach the two removed nodes as its children.
- The last remaining node is the root. Read each symbol's codeword off the path from the root to its leaf, writing for a left branch and for a right branch.
Each merge reduces the number of nodes by one, so the loop runs times; with a binary heap each iteration costs and the total is . If the probabilities arrive already sorted, two queues (one of leaves, one of merged nodes) give .
Proposition 5.2 (Huffman codes are prefix-free and complete). The code produced by Huffman's algorithm is prefix-free, and its Kraft sum is exactly .
Proof. Symbols sit only at leaves, and no leaf lies on the root-to-leaf path of another leaf, so no codeword is a prefix of another: the code is prefix-free.
For completeness, note that every internal node created in step 2 has exactly two children, so the tree is full. In a full binary tree the leaf depths satisfy , which is proved by induction on the number of internal nodes: a single leaf at depth gives , and replacing a leaf at depth by an internal node with two children at depth replaces by , leaving the sum unchanged.∎
A full tree means no wasted budget: unlike the Shannon code of the previous part, whose Kraft sum was , a Huffman code spends every bit of its allowance.
Intuition. Think of the probabilities as weights and each merge as tying two of them together with a string. The two lightest get tied first, so they hang lowest; heavy symbols stay near the top and get short codewords.
The key insight — and the reason greed works here — is that once two symbols are the rarest, nothing later in the construction can improve on making them siblings. Their combined weight is all that matters afterwards.
Example 5.3 (Huffman code for a dyadic source). Build a Huffman code for , , , .
Solution. Merge 1. The two smallest are and ( each). Merge into node with weight . Queue: .
Merge 2. The two smallest are and ( each; ties broken arbitrarily). Merge into with weight . Queue: .
Merge 3. Merge and into the root, weight .
Reading the paths ( = left, = right, with on the left of the root): , , , .
Expected length: bits.
Sanity check. Prefix-free: is not a prefix of , and is not a prefix of or ✓. Kraft sum: ✓, so the tree is full. Entropy: bits, so exactly — as it must be, since all probabilities are dyadic.□
Example 5.4 (Huffman code for a non-dyadic source). Build a Huffman code for — the distribution for which the Shannon code gave — and compare.
Solution. Merge 1. Smallest two: and node , weight . Queue: .
Merge 2. Smallest two: and node , weight . Queue: .
Merge 3. Merge to the root.
Depths: the symbol is at depth ; the symbol at depth ; the and symbols at depth . Codewords: , , , .
Sanity check. bits (computed in the previous part), so ✓ — and the excess over entropy is only bits. Compare with the Shannon code's on the same source: the Shannon lengths wasted bits per symbol, because they ignore how the rounding interacts across symbols. Kraft sum here: ✓, full tree.□
Pitfall (Ties and the shape of the tree). Ties in step 2 may be broken arbitrarily, and different choices give different codes with different codeword lengths — but always the same expected length. In the dyadic example, merging with instead of with is not allowed (their weights are not the two smallest), but where genuine ties occur the resulting trees can look quite different. Implementations that must interoperate therefore fix a deterministic tie-breaking rule, or transmit code lengths explicitly.
5.2Optimality of Huffman Codes
Huffman's algorithm is greedy, and greedy algorithms are usually wrong. That this one is right needs proof, and the proof is a model of its kind: two structural lemmas about optimal codes, then an induction that says merging is harmless.
Throughout, order the probabilities and call a prefix code optimal for if it minimises among all prefix codes.
Lemma 5.6 (Structure of an optimal code). For any distribution with there is an optimal prefix code such that:
- (more probable symbols get no longer codewords);
- the two longest codewords have equal length;
- the two longest codewords differ only in their last bit — that is, they are siblings in the tree — and they may be taken to belong to the two least probable symbols and .
Proof. (1) Let be optimal and suppose but . Form by swapping the codewords of and ; is still a prefix code with the same multiset of lengths. The change in expected length is
since and . That contradicts optimality of , so no such pair exists.
(2) Suppose the longest codeword is strictly longer than every other. No other codeword has as a prefix (prefix-freeness), and no other codeword is a prefix of ; deleting the last bit of therefore keeps the code prefix-free — the shortened string cannot be a prefix of another codeword, since such a codeword would then have the shortened string as a prefix and be at least as long as , contradicting uniqueness of the maximum. The deletion strictly decreases , contradicting optimality.
(3) By (2) there are at least two codewords of maximal length . Take one, ; its sibling (the string agreeing with except in the last bit) must be a codeword or have a codeword as a proper prefix — otherwise the subtree hanging there is empty and could be shortened, as in (2). Since has maximal length, the sibling must itself be a codeword. So maximal-length codewords come in sibling pairs. Finally, by (1) the symbols with maximal length are among the least probable; permuting codewords of equal length does not change , so we may relabel so that the sibling pair belongs to and .∎
Theorem 5.7 (Optimality of Huffman coding). For every distribution on a finite alphabet, the Huffman code is optimal: no prefix code (equivalently, by Kraft–McMillan, no uniquely decodable code) has smaller expected length.
Proof. Induction on the alphabet size .
Base case . Any prefix code needs two distinct codewords, so ; Huffman assigns and and achieves .
Induction step. Assume Huffman is optimal for every distribution on symbols. Given , let be the distribution on symbols obtained by merging the two smallest into one symbol of probability .
First, a bookkeeping identity. Codes on the merged alphabet and codes on the original alphabet in which are siblings correspond one to one: split the merged symbol's codeword into and , or conversely delete the last bit. Under this correspondence the expected lengths differ by a fixed amount,
because the two split symbols each gain one bit, contributing , while every other symbol is unchanged.
Now let be the Huffman code for . By construction it is obtained by splitting the merged symbol of the Huffman code for , so .
Let be any optimal code for . By Lemma Structure of an optimal code we may assume and are siblings in ; merging them gives a prefix code for with by . By the induction hypothesis . Therefore
Since was optimal, and the Huffman code is optimal too.∎
The proof also explains why greed is safe. The structure lemma says every optimal code contains the decision "make the two rarest symbols siblings" somewhere inside it; the algorithm simply makes that decision first, and identity shows that doing so costs a fixed amount regardless of what happens later.
Corollary 5.8 (Huffman codes obey the fundamental bound). The Huffman expected length satisfies
with if and only if every is a power of .
Proof. The lower bound and the equality condition come from the entropy lower bound for uniquely decodable codes. For the upper bound, the Shannon code is a prefix code with , and by optimality.∎
Corollary 5.9 (Huffman coding of blocks approaches the entropy rate). Let be the expected length of the Huffman code applied to blocks of symbols of a stationary source. Then
Proof. Apply the previous corollary to the single random variable over the alphabet , then divide by and let , using the definition of the entropy rate.∎
Intuition. Huffman gives you the best possible "comma-free" code, and the worst it can ever be is one bit per symbol above the theoretical floor.
That one bit is entirely the fault of integer arithmetic: a symbol of probability deserves a codeword of length bits and gets one of length . Blocking symbols together spreads a single rounding error over many symbols, which is why the excess shrinks like .
Example 5.10 (When the one-bit gap really bites). A binary source has . Compute , the Huffman expected length, and the efficiency. Then Huffman-code blocks of two symbols and recompute.
Solution. Single symbols. bits.
There are only two symbols, so the only prefix code is and bit. Efficiency ; the excess is bits — nearly the whole allowed bit.
Pairs. The block probabilities are , , , . Huffman merges with (), then that with (), then with . Lengths: , , , .
i.e. bits per symbol.
Sanity check. : indeed ✓. Blocking halved the per-symbol cost from to , exactly as the overhead predicts, and blocks of eight would bring it to about . To actually reach one needs blocks of thousands — or arithmetic coding, which is the subject of the next part.□
Pitfall (Optimal does not mean good). Huffman is optimal within the class of symbol codes for the given model. It cannot exploit memory (a first-order Huffman code on English text ignores that q is followed by u), it cannot spend a fractional bit, and it is helpless if the probabilities are wrong. Optimality is always relative to a class and a model; both restrictions are severe.
5.3Huffman Coding in Practice
Real formats — DEFLATE, JPEG, MP3 — use Huffman codes, but never in the naive form of the algorithm above. Four engineering issues dominate.
Definition 5.11 (Canonical Huffman code). A canonical Huffman code is the code obtained from a length vector by sorting symbols by and assigning codewords in increasing numerical order, incrementing the code value by at each symbol and shifting left when the length increases — exactly the cumulative construction used in the proof of Kraft's converse.
Proposition 5.12 (Canonical codes are as good and cheaper to transmit). A canonical Huffman code has the same codeword lengths, and hence the same expected length, as the Huffman code it is derived from; and it is fully determined by the length vector alone.
Proof. The construction assigns to the symbol of length the interval of the Kraft proof, so lengths are preserved and the code is prefix-free; expected length depends only on lengths. Since the assignment is a deterministic function of the sorted lengths, decoder and encoder agree given the lengths alone: a table of small integers rather than variable-length bit strings.∎
That proposition is why DEFLATE transmits a list of code lengths, themselves run-length and Huffman coded, rather than a tree. It also makes decoding fast: canonical codes can be decoded by comparing the input register against one threshold per length, without walking a tree.
- Length-limited Huffman. Hardware decoders need a bound (typically or ) so that a lookup table fits in cache. The package-merge algorithm finds the optimal code subject to in time; the cost in expected length is usually a fraction of a percent.
- Adaptive Huffman. The FGK and Vitter algorithms maintain the tree as symbols arrive, so the encoder need not make a first pass or transmit a table. They pay in speed and in a small redundancy, and have largely been displaced by adaptive arithmetic coding.
- Blocking and context. Since Huffman cannot spend fractional bits, real codecs apply it to derived symbols that are already close to independent — DEFLATE Huffman-codes literal/length and distance symbols produced by an LZ77 pass; JPEG Huffman-codes (run, size) pairs produced by run-length coding the quantised DCT coefficients.
Theorem 5.13 (Worst-case codeword length). For an alphabet of size , no Huffman codeword is longer than bits, and this bound is attained — for example by probabilities proportional to the Fibonacci numbers
Proof. Each merge in the algorithm increases by one the depth of the symbols in the merged subtrees, and there are exactly merges, so no depth can exceed . Attainment: if with , then at every step the newly created node has weight equal to the next Fibonacci number, hence is again one of the two smallest, so every merge involves the node created in the previous step. The tree degenerates into a path and the rarest symbol receives bits.∎
Example 5.14 (Huffman inside JPEG). In baseline JPEG, an block's quantised AC coefficients are converted to (run-length, magnitude-category) symbols, which are Huffman-coded; the extra bits identifying the value within a category are appended raw. Why is the category trick used instead of Huffman-coding the coefficient values directly?
Solution. A coefficient can take thousands of values, so a direct Huffman table would need thousands of entries — expensive to transmit and to store — while most entries would be used a handful of times per image.
Grouping values by magnitude category (; ; ; …) reduces the alphabet to about categories crossed with run lengths, i.e. a table of about entries. Within a category of size , all values are nearly equiprobable, so spending raw bits on them costs almost nothing above their entropy.
Sanity check. The scheme is exactly the Shannon-code idea applied twice: the category carries bits of genuinely skewed information and is worth Huffman-coding; the within-category offset carries bits of nearly uniform information and is not. Huffman-coding a uniform alphabet of size gives codewords of exactly bits, so the raw bits lose nothing — the table is saved for free.□
5.4The Splitting Construction
Shannon–Fano coding is the first systematic construction of an efficient prefix code, described by Shannon in 1948 and refined by Fano the same year. It is no longer the method of choice — Huffman is optimal and barely harder — but it is the cleanest illustration of top-down code design, and its analysis is where the bound was first established.
Two different constructions travel under the name "Shannon–Fano", and it is worth keeping them apart.
Definition 5.15 (Shannon's lengths). Shannon's code assigns and realises those lengths by the cumulative construction of Kraft's converse: sort by decreasing probability, set , and take the first bits of the binary expansion of .
Method 5.16 (Fano's splitting algorithm). Fano's code is built top-down.
- Sort the symbols in non-increasing order of probability.
- Split the sorted list into two consecutive groups whose total probabilities are as nearly equal as possible.
- Append to every codeword in the first group and to every codeword in the second.
- Recurse on each group until every group holds a single symbol.
Both produce prefix codes — Shannon's by Kraft's converse, Fano's because the recursion builds a binary tree with the symbols at its leaves — and both satisfy the fundamental bound.
Theorem 5.17 (Shannon's code satisfies ). The Shannon code is a prefix code and its expected length obeys .
Proof. The lengths satisfy Kraft's inequality, since and the sum to , so the cumulative construction of Kraft's converse realises them as a prefix code. Averaging the pointwise bounds against gives . (This is the fundamental bound established earlier; it is repeated here because Shannon's lengths are the code it was proved for.)∎
Proposition 5.18 (Fano's code is bracketed on both sides). Fano's code is a prefix code, so ; and , so it is never better than the optimum.
Proof. The recursion assigns symbols to the leaves of a binary tree, so no codeword is a prefix of another, and the entropy lower bound for uniquely decodable codes gives . The second inequality is Huffman optimality.∎
Remark (The upper bound for Fano's code). That Fano's splitting also satisfies is classical, but its proof is a delicate induction over the splitting recursion — the difficulty is that a greedy split can be forced far from balance by a single dominant symbol — and we do not give it here. What the results above do give without extra work is the two-sided bracket together with ; for every distribution appearing in this chapter, is computed directly and checked against .
Intuition. Fano's rule is "twenty questions with a balanced question": ask a yes/no question that splits the probability as evenly as you can, and the answer carries a full bit of information.
The reason it is not optimal is that the greedy split looks one level ahead. Balancing against at the top looks perfect, but it commits the most probable symbol to sharing its side with another, and so to a two-bit codeword.
Example 5.19 (Fano's code on a dyadic source). Construct Fano's code for (already sorted).
Solution. Level 1. Split : masses and , a perfect balance. Assign to the left, to the right. , finished.
Level 2 on (prefix 1). Split : versus . So , and carry the prefix 11.
Level 3 on . Split : each. , .
Lengths and
Sanity check. bits, so exactly, as the dyadic equality condition requires. Shannon's lengths agree here too: , , , . And the Huffman code built earlier is the same code. On dyadic distributions all three constructions coincide.□
5.5Where Fano's Heuristic Loses to Huffman
Fano's code is top-down and greedy on balance; Huffman's is bottom-up and greedy on rarity. Only the second is optimal, and the gap is usually tiny but always in the same direction.
Proposition 5.20 (Fano's code is never better than Huffman's). For every distribution, , and the inequality is strict for some distributions.
Proof. Fano's construction yields a prefix code, and the Huffman code minimises expected length over all prefix codes by the optimality theorem, so . Strictness is exhibited by the example below.∎
Example 5.21 (A distribution where the heuristic is strictly worse). Compare Fano's code and the Huffman code on .
Solution. Fano. The most balanced consecutive split of the sorted list is against , i.e. against ; every other cut is further from ( against , or against ). The left pair splits once more, giving both symbols length . On the right, the best cut is against , so that symbol has length and the last two have length . Lengths :
Huffman. Merge ; then the two smallest are and , merge to ; then ; then . Depths: the symbol is at depth , the other four at depth . Lengths :
Entropy.
Sanity check. Both codes satisfy , i.e. ✓, and Huffman wins by bits per symbol, as the proposition requires. The diagnosis is instructive: Fano's top-level balance is excellent ( versus ) but it costs the most probable symbol a second bit, and bits of waste is not repaid by the better balance further down. Huffman's Kraft sums are equal ( in both codes), so this is not a matter of wasted budget but of where the budget is spent.□
Pitfall (Shannon's lengths are not Fano's lengths). For the distribution above, Shannon's lengths are and , giving and — worse than both. The three constructions agree on dyadic distributions and diverge elsewhere, so "Shannon–Fano coding" is an ambiguous name; say which one you mean.
Theorem 5.22 (Competitive optimality of the Shannon code). Let be the Shannon lengths and let be the lengths of any other uniquely decodable code. Then for every ,
No competitor can beat the Shannon code by more than a few bits except with exponentially small probability — even though a competitor may beat it on average.
Proof. Using ,
Bounding the probability of the event by summing over the strings in it, and on each such string using ,
the last step by the Kraft–McMillan inequality for the competing code.∎
This is the sense in which the Shannon code is hard to beat per message rather than on average: an opponent who does better on some strings must do much worse on others, and the worse cases carry most of the probability.
5.6Why the History Matters
Shannon's 1948 paper proved that was the compression limit and gave the lengths to show the limit was nearly attainable; Fano's contemporaneous splitting rule gave a practical recipe. Neither was optimal, and neither author claimed otherwise — the question "what is the best prefix code?" was left open, and Fano set it as a term project in his MIT information theory course in 1951.
David Huffman, a student in that course, chose the project over the final exam. After weeks of failing to improve the top-down approach, he inverted it: instead of asking which symbol gets which bit first, ask which two symbols are the last to be distinguished. The bottom-up merge fell out immediately, and with it the optimality proof.
Three lessons from the episode survive in the material of this chapter.
- The right greedy direction is not obvious. Both algorithms are greedy; only the bottom-up one has the exchange property that makes greed provably safe, and that property is exactly Lemma Structure of an optimal code.
- Optimality within a class is not the end. Huffman closed the prefix-code question, and the one-bit gap remained, which is what drove the development of arithmetic coding (Rissanen and Pasco, 1976) two decades later.
- The old ideas do not disappear. Shannon's lengths reappear as the length formula of arithmetic coding; Fano's balanced splitting reappears in the design of canonical and length-limited codes; and the cumulative-sum construction used for Shannon's code is exactly the interval arithmetic of the modern coder.
Intuition. Shannon said: give common things short names. Fano said: here is a way to do it — halve the probability at each question. Huffman said: do it backwards, and here is the proof that nothing does better.
The remaining bit of waste came not from any of them but from the alphabet of output symbols: bits are indivisible. Arithmetic coding fixed that by giving up on codewords entirely.
Example 5.23 (Reading the historical progression off one source). For line up Shannon's, Fano's and Huffman's codes and the entropy.
Solution. Entropy. bits.
Shannon. , bits.
Fano. The most balanced split is ( against ; the alternative against is against ). Then , then the last pair. Lengths , bits.
Huffman. Lengths , bits — identical to Fano's here.
Sanity check. ✓. Fano matches Huffman on this distribution and loses on the five-symbol example above, which is the honest summary of the heuristic: usually excellent, occasionally optimal, never guaranteed. Shannon's lengths are the weakest of the three because they round each symbol independently, ignoring how the rounding interacts across the alphabet.□
- Assuming Huffman achieves the entropy exactly. It achieves ; equality holds only for dyadic probabilities. For a very skewed binary source the gap approaches a full bit, which can be a factor of ten in rate.
- Comparing Huffman codes by their codewords instead of their lengths. Tie-breaking changes the codewords; only the length vector, and hence , is canonical.
- Forgetting the cost of the table. A two-pass Huffman coder must transmit the code (or the lengths). On small inputs this overhead can exceed the savings, which is why DEFLATE offers a fixed, pre-agreed table as an option.
- Assuming the rarest symbol gets a short codeword because the tree is "balanced". In the worst case it gets bits; Huffman trees are balanced only when the distribution is near uniform.
- Using a stale model. Huffman assumes the probabilities are known and fixed. On data whose statistics drift, adaptive coding, or re-estimating per block, is essential.
- Believing Huffman handles memory. Symbol-by-symbol Huffman coding is blind to correlation; the gain from context modelling usually dwarfs the gain from optimal symbol coding.
- Believing Fano's code is optimal. It is not; the five-symbol example is a genuine counterexample, and the proposition above says the direction of the error is always the same.
- Splitting by count instead of by mass. The rule balances the *sum of probabilities* of the two groups, not the number of symbols in them.
- Forgetting to sort first. Fano's construction requires non-increasing probabilities and splits only into *consecutive* groups; splitting an unsorted list can produce a code far from optimal.
- Conflating Shannon's lengths with Fano's algorithm. They are different codes with different lengths, as the pitfall above shows.
- Ignoring memory. Like Huffman, Fano coding is symbol-by-symbol and blind to correlation; blocking or context modelling is required to capture it.
- Assuming it is used in modern standards. It is not. Where a simple prefix code is wanted, canonical Huffman is used; where the last fraction of a bit matters, arithmetic coding or ANS.