Module contents
Lesson 5 of 19Core 100 min

Prefix codes, Kraft's inequality and Huffman coding

Build symbol-by-symbol codes from prefix trees, derive the Kraft–McMillan inequality and the bounds H ≤ L* < H + 1, and prove Huffman optimality. Connect compression to learning by measuring the D(p‖q) extra ideal bits per symbol from coding with a mismatched model q.

After this lesson you can

  • Construct prefix codes and use their trees to check instantaneous decodability.
  • Prove Kraft’s inequality and state McMillan’s extension to uniquely decodable codes.
  • Derive the ideal lengths ℓ = −log p with Lagrange multipliers and prove H ≤ L* < H + 1.
  • Implement Huffman coding and use exchange arguments to prove optimality.
  • Quantify the cost of designing a code for q when the source is p.

Before you start

Motivation: from Morse to zip

A source emits four symbols with probabilities p=(0.4,0.3,0.2,0.1)p = (0.4, 0.3, 0.2, 0.1). Its entropy is H⁡(p)=1.846\Ent(p) = 1.846 bits, and the source coding theorem promises that encoding long blocks lets us approach that figure arbitrarily closely. But a real compressor does not encode infinite blocks: it assigns each symbol a word of zeros and ones, concatenates the words and expects the receiver to separate them. What does that symbol-by-symbol code cost? Fixed-length words need 2 bits. Code 0,10,110,1110, 10, 110, 111 gives 0.4⋅1+0.3⋅2+0.2⋅3+0.1⋅3=1.90.4 \cdot 1 + 0.3 \cdot 2 + 0.2 \cdot 3 + 0.1 \cdot 3 = 1.9 bits. Using the lengths suggested by surprise, ⌈−log⁡2p⌉=(2,2,3,4)\lceil -\log_2 p \rceil = (2, 2, 3, 4), gives 2.42.4. Three codes, three costs, all above 1.8461.846. Is 1.91.9 the best possible? Why can’t we go below 1.8461.846? How much is lost by not knowing pp well?

These old questions, which Samuel Morse faced when assigning “e” one dot and “q” four signals, are answered with mathematical precision in this lesson. Morse code also hides an instructive trap: one dot is “e”, two consecutive dots are “i”, so the signal sequence alone is ambiguous and the telegraph operator needs a pause between letters. Morse is actually a ternary code (dot, dash and silence). With a binary alphabet that pause does not exist, and word separation must be guaranteed by the code’s structure itself. This gives the lesson’s ideas:

  • Prefix codes. A simple condition, that no word begins another, allows decoding on the fly and can be read as a tree.
  • The Kraft–McMillan inequality. Which length lists are possible? This is a budget condition: each ℓ\ell-bit word consumes 2−ℓ2^{-\ell} and the total cannot exceed 1.
  • The bounds H⁡(p)≤L∗<H⁡(p)+1\Ent(p) \le L^* < \Ent(p) + 1. The best symbol-by-symbol code cannot beat entropy and exceeds it by at most one bit.
  • Huffman. A ten-line greedy algorithm constructs the optimal code, with an exchange proof of optimality.
  • The wrong model. If the code is designed for qq but data come from pp, the excess is exactly KL⁡(p ∥ q)\KL(p\,\|\,q) bits per symbol. This bridges compression and learning: the cross-entropy loss used to train language models is a code length.

This is not engineering folklore. The DEFLATE code in zip, gzip and PNG (repetition search, LZ77, followed by Huffman codes) and JPEG’s entropy stage rest on what follows. Unless otherwise stated, log⁡\log is base-2 logarithm, lengths are measured in bits and the code alphabet is binary {0,1}\{0, 1\}; the end of the Kraft section describes what changes for an alphabet of DD symbols.

Codes, words and instantaneous decoding

Let X\mathcal{X} be a finite source-symbol alphabet (the source is a random variable XX with mass pp) and {0,1}∗\{0, 1\}^* the set of finite binary strings. A code is a map C:X→{0,1}∗C : \mathcal{X} \to \{0, 1\}^*; C(x)C(x) is the word for xx and ℓ(x)=∣C(x)∣\ell(x) = \abs{C(x)} its length. We always assume p(x)>0p(x) > 0 for every xx (an impossible symbol needs no word) and nonempty words. Code quality is measured by its mean length

L(C)=∑x∈Xp(x) ℓ(x)=E[ℓ(X)].L(C) = \sum_{x \in \mathcal{X}} p(x)\, \ell(x) = \E[\ell(X)] .

To encode a sequence x1x2…xnx_1 x_2 \dots x_n, concatenate the words, C(x1)C(x2)⋯C(xn)C(x_1)C(x_2)\cdots C(x_n). For this to work, the receiver must be able to invert it. There are three levels of requirement, each stronger than the last:

  • Nonsingular: x≠x′x \ne x' implies C(x)≠C(x′)C(x) \ne C(x'). Enough to describe one symbol, but not a sequence: with C(a)=0C(a) = 0, C(b)=1C(b) = 1, C(c)=01C(c) = 01, the string 0101 may be cc or abab.
  • Uniquely decodable (UD): concatenation is injective, meaning distinct symbol sequences (of any length) produce distinct bit strings.
  • Prefix (or instantaneous): no word is a prefix of another. This is the class we will almost always use.

Each class contains the next: prefix implies UD implies nonsingular, and inclusions are strict. The first follows from the decoding algorithm itself. To decode a prefix code, read bit by bit and, the moment the bits read match a word, emit its symbol and start again. There is never a need to look at further bits to see whether “that” could start another word: no word starts with this one. Hence instantaneous, with no delay or buffering.

A prefix code is a tree

Draw the full binary tree: each node has two outgoing edges, the left labeled 00 and the right 11. A node at depth ℓ\ell is identified by the ℓ\ell-bit string from the root to it. A code is a set of nodes, one per symbol, and is prefix precisely when no chosen node is an ancestor of another (a word’s descendants are unusable because each has that word as prefix). A word’s length is its depth. The “twenty questions” of lesson 1 are this same tree read as an interrogation: each bit is a yes-or-no answer, and decoding ends at a leaf. For the rooted tree theory used here see rooted tree.

This picture turns a combinatorial problem (whether ℓ1,…,ℓm\ell_1, \dots, \ell_m are the lengths of a prefix code) into a problem of space. There are finitely many nodes: choosing one at depth ℓ\ell eliminates its whole subtree. But a node at depth ℓ\ell does not “cost” the same as one at depth ℓ+1\ell + 1: half the tree (50%) hangs from each child of the root, a quarter from each grandchild, and generally a node at depth ℓ\ell governs fraction 2−ℓ2^{-\ell} of all tree leaves. That fraction is the word’s price. The figure shows the tree laid out in rows, with each node’s width proportional to its price.

InteractiveThe Kraft budget
ℓ = 1ℓ = 2ℓ = 3ℓ = 4ℓ = 5ℓ = 6A 0B 10C 110D 111EBudget consumed, word by wordABCDE10
A0B10C110D111E0000?
1 bit
2 bits
3 bits
3 bits
4 bits
∑2−ℓ\sum 2^{-\ell}1.0625 (68/64)
Free budget0 (overflow)
Words without room1
∑2−ℓ=1.0625>1\sum 2^{-\ell} = 1.0625 > 1: no prefix code exists with these lengths. There is no room for symbol E. Trying again from the left, candidate 0000 starts with the word of A (0), which would be its prefix.
Five symbols A through E receive lengths from sliders. At depth ℓ\ell each node occupies width 2−ℓ2^{-\ell} of the total budget, which is 1: the left half of a row is the branch beginning with 0 and the right half starts with 1. Words are placed in increasing length order, as far left as possible, blocking everything below them (light shading). Dashed nodes are what remains free. With starting point ∑2−ℓ=1.0625\sum 2^{-\ell} = 1.0625: E has no room and the attempt (red) falls on a word that would be its prefix. Shorten or lengthen the lengths: for which sums does a code exist? Try the ‘Full tree’ example. Try constructing one with ∑2−ℓ\sum 2^{-\ell} slightly above 1 and check whether you can.

What the figure suggests, and what is proved next, is that the sum is the only obstacle. Any length list whose prices sum to at most 1 has room for all words; once the sum exceeds 1, the last ones do not fit, however they are placed.

The Kraft–McMillan inequality

The proof has three parts: the condition is necessary for prefix codes, sufficient (by construction), and necessary even for UD codes.

Proof

Necessity for prefix codes. Let ℓmax⁡=max⁡iℓi\ell_{\max} = \max_i \ell_i and consider the full binary tree of depth ℓmax⁡\ell_{\max}, with 2ℓmax⁡2^{\ell_{\max}} leaves. Word wiw_i is a node at depth ℓi\ell_i, below which lie exactly 2ℓmax⁡−ℓi2^{\ell_{\max} - \ell_i} leaves of the full tree (the remaining ℓmax⁡−ℓi\ell_{\max} - \ell_i bits may be arbitrary). If wiw_i and wjw_j, with i≠ji \ne j, shared a leaf, that leaf would be a string beginning with both wiw_i and wjw_j, and the shorter would be a prefix of the other: contradiction. Hence the leaf sets are disjoint, and their union fits in the 2ℓmax⁡2^{\ell_{\max}} leaves:

∑i2ℓmax⁡−ℓi≤2ℓmax⁡⟹∑i2−ℓi≤1.\sum_{i} 2^{\ell_{\max} - \ell_i} \le 2^{\ell_{\max}} \quad\Longrightarrow\quad \sum_i 2^{-\ell_i} \le 1 .

Equality holds if and only if leaves descending from words cover the whole tree, i.e. no leaf remains free.

Sufficiency (construction). Suppose ∑i2−ℓi≤1\sum_i 2^{-\ell_i} \le 1 and order the lengths, ℓ1≤ℓ2≤⋯≤ℓm\ell_1 \le \ell_2 \le \dots \le \ell_m. Define cumulative sums

ci=∑j<i2−ℓj,c1=0,c_i = \sum_{j < i} 2^{-\ell_j}, \qquad c_1 = 0,

and let wiw_i be the string formed by the first ℓi\ell_i binary digits of cic_i. This makes sense: cic_i is a multiple of 2−ℓi−12^{-\ell_{i-1}} and ℓi−1≤ℓi\ell_{i-1} \le \ell_i, so cic_i has a finite binary expansion of at most ℓi\ell_i digits, all captured by wiw_i; and ci≤∑j2−ℓj−2−ℓi<1c_i \le \sum_{j} 2^{-\ell_j} - 2^{-\ell_i} < 1, so all those digits are to the right of the binary point. Viewed as an interval, wiw_i corresponds to dyadic interval Ii=[ci,ci+2−ℓi)I_i = [c_i, c_i + 2^{-\ell_i}). If wjw_j were a prefix of wiw_i with j<ij < i, point cic_i would lie in IjI_j, i.e. ci<cj+2−ℓj=cj+1c_i < c_j + 2^{-\ell_j} = c_{j+1}. But ci≥cj+1c_i \ge c_{j+1} because cumulative sums increase with the index. Contradiction: no wjw_j is a prefix of another.

McMillan: necessity for UD codes. Let CC be uniquely decodable, with lengths ℓ(x)≤ℓmax⁡\ell(x) \le \ell_{\max} and S=∑x2−ℓ(x)S = \sum_x 2^{-\ell(x)}. For n≥1n \ge 1,

Sn=∑x1,…,xn2−(ℓ(x1)+⋯+ℓ(xn))=∑m=nnℓmax⁡an(m) 2−m,S^n = \sum_{x_1, \dots, x_n} 2^{-(\ell(x_1) + \cdots + \ell(x_n))} = \sum_{m=n}^{n\ell_{\max}} a_n(m)\, 2^{-m},

where an(m)a_n(m) counts nn-tuples (x1,…,xn)(x_1, \dots, x_n) whose concatenation C(x1)⋯C(xn)C(x_1)\cdots C(x_n) has mm bits. Since CC is UD, distinct tuples give distinct strings, and there are only 2m2^m strings of mm bits: an(m)≤2ma_n(m) \le 2^m. Thus each summand is at most 1 and

Sn≤nℓmax⁡−n+1≤nℓmax⁡⟹S≤(nℓmax⁡)1/n→n→∞1.S^n \le n\ell_{\max} - n + 1 \le n\ell_{\max} \quad\Longrightarrow\quad S \le (n\ell_{\max})^{1/n} \xrightarrow[n \to \infty]{} 1 .

Since nn is arbitrary, S≤1S \le 1.

∎

Three things to retain.

  1. McMillan closes the door to tricks. Since every UD code’s lengths satisfy Kraft, a prefix code exists with the same lengths (the construction above) and thus the same mean length. Giving up instantaneous decoding saves not a single bit on average: to find the best code, prefix codes suffice. This is why hardly anyone discusses UD non-prefix codes.
  2. Kraft only concerns lengths. It does not specify which words to use, and indeed there are many equivalent choices (swapping 0 and 1 at any internal node gives another prefix code with the same lengths). It does say which lengths are possible, and that is all an optimization problem needs: mean length depends only on lengths.
  3. For a code alphabet of DD symbols the proof is the same, counting Dℓmax⁡−ℓiD^{\ell_{\max} - \ell_i} leaves: the condition is ∑iD−ℓi≤1\sum_i D^{-\ell_i} \le 1. Exercises and figures keep D=2D = 2.

An immediate consequence of the construction is an operational test: lengths (1,2,3,3)(1, 2, 3, 3) sum to 12+14+18+18=1\tfrac12 + \tfrac14 + \tfrac18 + \tfrac18 = 1, so a prefix code exists and gives {0,10,110,111}\{0, 10, 110, 111\} from the motivation. Lengths (1,2,2,3)(1, 2, 2, 3) sum to 1.125>11.125 > 1 and no code is possible, prefix or UD. This is exactly what happens to EE in the figure when it attempts to enter an already full tree.

Ideal lengths and the lower bound

We can now state the optimization problem: choose lengths to minimize L=∑ipiℓiL = \sum_i p_i \ell_i subject to ∑i2−ℓi≤1\sum_i 2^{-\ell_i} \le 1 and ℓi\ell_i being integers. The integer constraint makes the problem hard to handle by hand. A classic trick is to drop it first, solve the relaxed problem with ℓi∈R\ell_i \in \R, and see what remains.

The relaxed problem is convex: the objective is linear in ℓ\ell and the constraint g(ℓ)=∑i2−ℓi−1≤0g(\ell) = \sum_i 2^{-\ell_i} - 1 \le 0 is convex (a sum of exponentials). Lagrange optimality conditions are therefore sufficient. With Lagrangian L(ℓ,λ)=∑ipiℓi+λ(∑i2−ℓi−1)\mathcal{L}(\ell, \lambda) = \sum_i p_i \ell_i + \lambda\big(\sum_i 2^{-\ell_i} - 1\big):

∂L∂ℓi=pi−λln⁡2⋅2−ℓi=0\pd{\mathcal{L}}{\ell_i} = p_i - \lambda \ln 2 \cdot 2^{-\ell_i} = 0
Stationarity condition. Since pi>0p_i > 0, we need λ>0\lambda > 0 and the constraint is active.
1/4

This is a neat result: surprise −log⁡p(x)-\log p(x) from the first lesson is the ideal length of the word for xx, and entropy is the ideal cost. Since integer lengths are a special case of real lengths, the relaxed minimum H⁡(p)\Ent(p) is already a lower bound for any code. But a direct, much more informative proof also tells us how much is lost when lengths are not ideal. This is the lesson’s central identity.

Proof

With 2−ℓ(x)=S r(x)2^{-\ell(x)} = S\,r(x) we have ℓ(x)=−log⁡S−log⁡r(x)\ell(x) = -\log S - \log r(x), and

L−H⁡(p)=∑xp(x)(ℓ(x)+log⁡p(x))=∑xp(x)log⁡p(x)2−ℓ(x)=∑xp(x)log⁡p(x)S r(x)=KL⁡(p ∥ r)−log⁡S.■L - \Ent(p) = \sum_x p(x)\big(\ell(x) + \log p(x)\big) = \sum_x p(x) \log\frac{p(x)}{2^{-\ell(x)}} = \sum_x p(x) \log\frac{p(x)}{S\, r(x)} = \KL(p\,\|\,r) - \log S. \qquad\blacksquare∎

Both summands are nonnegative, each with an interpretation. KL⁡(p ∥ r)≥0\KL(p\,\|\,r) \ge 0 by Gibbs’ inequality: it is the price of lengths (normalized, rr) describing pp poorly. log⁡(1/S)≥0\log(1/S) \ge 0 when Kraft holds: this is the wasted budget, bits that could have been saved because the tree has free leaves. It quantifies the previous figure.

By Kraft (or McMillan), S≤1S \le 1, so log⁡(1/S)≥0\log(1/S) \ge 0; by Gibbs, KL⁡(p ∥ r)≥0\KL(p\,\|\,r) \ge 0. Equality holds only if S=1S = 1 and r=pr = p, i.e. 2−ℓ(x)=p(x)2^{-\ell(x)} = p(x), and since ℓ(x)\ell(x) is an integer, p(x)p(x) is a power of 12\tfrac12. With p=(0.4,0.3,0.2,0.1)p = (0.4, 0.3, 0.2, 0.1) none of the probabilities is, so no code has L=1.846L = 1.846. Check the motivation’s numbers: for lengths (1,2,3,3)(1, 2, 3, 3) we have S=1S = 1 and L−H⁡(p)=0.0536=KL⁡(p ∥ r)L - \Ent(p) = 0.0536 = \KL(p\,\|\,r) with r=(12,14,18,18)r = (\tfrac12, \tfrac14, \tfrac18, \tfrac18); for (2,2,3,4)(2, 2, 3, 4) we have S=0.6875S = 0.6875, and excess 0.55360.5536 splits into 0.01300.0130 of divergence and 0.5406=log⁡2(1/0.6875)0.5406 = \log_2(1/0.6875) of unused leaves. That second code wastes nearly all its excess in the unfilled tree.

The upper bound: Shannon coding

The lower bound does not say we can get close. This does: just round ideal lengths up.

Let ℓ(x)=⌈−log⁡p(x)⌉\ell(x) = \lceil -\log p(x) \rceil. Since ℓ(x)≥−log⁡p(x)\ell(x) \ge -\log p(x), we have 2−ℓ(x)≤p(x)2^{-\ell(x)} \le p(x) and therefore

∑x2−ℓ(x)≤∑xp(x)=1,\sum_x 2^{-\ell(x)} \le \sum_x p(x) = 1 ,

that is, Kraft holds and there is a prefix code with those lengths: the Shannon code (using the canonical construction from the preceding section). Its mean length is

LShannon=∑xp(x)⌈−log⁡p(x)⌉<∑xp(x)(−log⁡p(x)+1)=H⁡(p)+1.L_{\text{Shannon}} = \sum_x p(x)\lceil -\log p(x)\rceil < \sum_x p(x)\big(-\log p(x) + 1\big) = \Ent(p) + 1 .

The lower bound is the previous corollary (and holds for any UD code); the upper bound is the Shannon code. For blocks apply the same result to variable Xk=(X1,…,Xk)X^k = (X_1, \dots, X_k), whose entropy is k H⁡(p)k\,\Ent(p) since the XiX_i are independent (lesson 1). This is the lossless variable-length version of the source coding theorem: the asymptotic version in lesson 4 said one can approach H⁡(p)\Ent(p) with vanishing error and long blocks, and this says the same with no error, real prefix codes, and explicit excess decreasing as 1/k1/k.

Two often-forgotten nuances:

  • The Shannon code is not optimal. With p=(0.4,0.3,0.2,0.1)p = (0.4, 0.3, 0.2, 0.1) it gives L=2.4L = 2.4 (even worse than fixed length 2 bits) and with p=(0.99,0.01)p = (0.99, 0.01) gives 0.99⋅1+0.01⋅7=1.060.99 \cdot 1 + 0.01 \cdot 7 = 1.06 bits, although {0,1}\{0, 1\} with 1 bit suffices. Rounding lengths separately does not consider the whole and leaves free leaves in the tree (the log⁡(1/S)\log(1/S) in the identity). An algorithm must jointly optimize integer lengths.
  • The bound H⁡+1\Ent + 1 cannot be improved for symbol-by-symbol codes. With p=(1−ε,ε)p = (1-\varepsilon, \varepsilon) entropy tends to 0 as ε→0\varepsilon \to 0, but any code on two symbols needs at least one bit per symbol: L∗=1L^* = 1. The excess approaches 1. This case dominates later when discussing Huffman’s limits.

The Huffman algorithm

In 1951 David Huffman was a doctoral student at MIT taking Robert Fano’s information theory course, where students chose between a final exam and a paper: find the minimum-mean-length binary code. Fano himself had proposed a top-down code (splitting the alphabet into two groups of similar probability, called Shannon–Fano coding) that is not always optimal. Huffman, unaware the problem was open, found the optimum by building the tree bottom up and published it in 1952 in a short paper: A Method for the Construction of Minimum-Redundancy Codes.

It takes n−1n - 1 merges. With a priority queue implemented as a binary heap, each operation costs O(log⁡n)\bigO(\log n) and the whole algorithm O(nlog⁡n)\bigO(n \log n). If probabilities are already sorted, two ordinary queues suffice (one for leaves and one for created nodes, which emerge in increasing order) at cost O(n)\bigO(n). Try the figure: choose an example and reproduce the construction, enter frequencies, or paste text.

InteractiveHuffman step by step
Priority queue (smallest weight first)
abdc100
010101abcd3060100400.400300.3010100.10110200.20111
Complete tree
Mean bits per symbol
Entropy
1.846
Huffman
1.900
Shannon
2.400
Fixed length
2.000
Frequencies or text
Sum of merged weights1.900 bits
Huffman LL1.900 bits
Entropy HH1.846 bits
Shannon ⌈−log⁡p⌉\lceil -\log p \rceil2.400 bits
Fixed length2 bits
Tree complete in 3 steps. Internal-node weights sum to L=1.900L = 1.900 bits per symbol, exactly the mean code length. Rounding to integer lengths costs L−H=0.054L - H = 0.054 bits.
Top: the priority queue with live weights; orange marks the two to merge next, magenta the newly created node. Below: the forest of trees growing toward the root. At the end, each leaf shows its word, and bars compare the mean bits for Huffman, Shannon code ⌈−log⁡p⌉\lceil -\log p \rceil, fixed length and entropy. Press ▶ with p=(0.4,0.3,0.2,0.1)p = (0.4, 0.3, 0.2, 0.1) and watch ‘sum of merged weights’: what quantity ends up equaling mean length? Then try the dyadic example: what does rounding cost? Also try ‘uniform over 8 symbols’. Finally paste your own text.

With p=(0.4,0.3,0.2,0.1)p = (0.4, 0.3, 0.2, 0.1): merge 0.1+0.2=0.30.1 + 0.2 = 0.3 and the queue becomes (0.3,0.3,0.4)(0.3, 0.3, 0.4); then 0.3+0.3=0.60.3 + 0.3 = 0.6, and finally 0.4+0.6=10.4 + 0.6 = 1. The weights of the three internal nodes sum to 0.3+0.6+1=1.90.3 + 0.6 + 1 = 1.9, exactly the mean length of the resulting code {0,10,110,111}\{0, 10, 110, 111\}. This is no coincidence, and the identity explains what the figure shows.

The reason is counting: a leaf at depth ℓ\ell has exactly ℓ\ell internal ancestors (including the root), so its probability is added ℓ\ell times in the total, and ∑vpeso⁡(v)=∑xp(x) ℓ(x)\sum_v \operatorname{peso}(v) = \sum_x p(x)\,\ell(x). This makes Huffman a cost procedure: each merge pays the weight of the created node, and merging the lightest is the greedy way to make each payment as small as possible.

Why it is optimal

A greedy algorithm need not succeed: removing the two lightest is a local decision, and the global optimum might require another. The proof uses two lemmas, one exchange and one reduction to a smaller problem. Order the symbols, p1≥p2≥⋯≥pn>0p_1 \ge p_2 \ge \dots \ge p_n > 0, with n≥2n \ge 2.

Proof

Let CC be an optimal prefix code and TT its tree.

(a) More probable symbols have shorter words. If pi>pjp_i > p_j and ℓi>ℓj\ell_i > \ell_j, swapping words of ii and jj gives another prefix code, with mean length

L′−L=piℓj+pjℓi−piℓi−pjℓj=(pi−pj)(ℓj−ℓi)<0,L' - L = p_i \ell_j + p_j \ell_i - p_i \ell_i - p_j \ell_j = (p_i - p_j)(\ell_j - \ell_i) < 0 ,

contradicting optimality of CC. Thus pi>pjp_i > p_j implies ℓi≤ℓj\ell_i \le \ell_j.

(b) The tree of CC is full. If an internal node had only one child, it could be removed (raising its entire subtree one level), shortening all words below by one bit, all with positive probability: LL would strictly decrease. Contradiction. Thus every internal node has two children.

(c) Siblings at maximum depth. Let vv be a maximum-depth leaf. By (b) it has a sibling v′v', and v′v' is a leaf: otherwise it would have descendants deeper than vv. Both are thus at maximum depth ℓmax⁡\ell_{\max}. We must put symbols nn and n−1n - 1 there. Let ss be the symbol of vv, and suppose s≠ns \ne n. If ℓn=ℓmax⁡\ell_n = \ell_{\max}, swapping words of ss and nn does not change LL because they have equal lengths. If ℓn<ℓmax⁡\ell_n < \ell_{\max}, then ps≤pnp_s \le p_n: from ps>pnp_s > p_n, (a) would imply ℓs≤ℓn<ℓmax⁡=ℓs\ell_s \le \ell_n < \ell_{\max} = \ell_s, absurd. Since pnp_n is the minimum probability, ps=pnp_s = p_n, and the swap changes LL by (ps−pn)(ℓn−ℓs)=0(p_s - p_n)(\ell_n - \ell_s) = 0. In either case the code stays optimal and, without loss of generality, nn is at vv. Let t≠nt \ne n be the symbol of v′v'. The same reasoning, with n−1n - 1 in the role of nn (pn−1p_{n-1} is minimum among symbols other than nn), lets us swap tt and n−1n - 1 without changing LL or moving nn. The resulting code is optimal and has n−1n - 1 and nn as siblings at maximum depth.

∎

The identity is immediate: the two new words are one bit longer than the merged one and the rest is unchanged, so mean length increases by (pn−1+pn)⋅1(p_{n-1} + p_n) \cdot 1. Conversely, if two leaves are siblings, replacing them with their parent gives a valid prefix code on p′p'.

Proof

By induction on nn (structural induction on the tree construction; see structural induction). For n=2n = 2 the only possible code is {0,1}\{0, 1\}, which Huffman gives. Assume the result for n−1n - 1 symbols and let pp have nn symbols. Step 2 merges the two lightest, n−1n - 1 and nn, and the rest of the algorithm is exactly Huffman on p′p'. By hypothesis, that remainder produces an optimal code H′H' for p′p', and Huffman code HH for pp is its expansion: L(H)=L(H′)+pn−1+pn=L∗(p′)+pn−1+pnL(H) = L(H') + p_{n-1} + p_n = L^*(p') + p_{n-1} + p_n by the reduction lemma.

Now let CC be an optimal code for pp in which n−1n - 1 and nn are siblings (it exists by the exchange lemma). By the converse of the reduction lemma, it expands a C′C' for p′p', so

L∗(p)=L(C)=L(C′)+pn−1+pn≥L∗(p′)+pn−1+pn=L(H).L^*(p) = L(C) = L(C') + p_{n-1} + p_n \ge L^*(p') + p_{n-1} + p_n = L(H) .

Since also L(H)≥L∗(p)L(H) \ge L^*(p) by definition of optimality, L(H)=L∗(p)L(H) = L^*(p).

∎

This is an exchange argument typical of greedy algorithms (exchange argument): yielding on the local decision is shown never to improve the result. The proof does not say the optimum is unique: when weights tie, several Huffman codes exist, all with the same LL but different length distributions. In practice it is useful to break ties so newly created nodes emerge after equal-weight leaves: among optima this gives minimum length variance, requiring least buffering on a constant-rate channel. The figure (and implementation below) does this.

The price of the wrong model

Huffman coding is optimal for pp. In practice pp is unknown: it is estimated, assumed or inherited from another dataset. Imagine designing a code for distribution qq, with lengths ℓ(x)=−log⁡q(x)\ell(x) = -\log q(x) (ideal, unrounded for now), and data actually come from pp. Mean length is

Ep[ℓ(X)]=∑xp(x)(−log⁡q(x))=H(p,q),\E_p[\ell(X)] = \sum_x p(x) \big(-\log q(x)\big) = H(p, q) ,

the cross entropy (lesson 6 studies it deeply). By the redundancy identity, with S=1S = 1 and r=qr = q:

H(p,q)−H⁡(p)=KL⁡(p ∥ q).H(p, q) - \Ent(p) = \KL(p\,\|\,q) .

Kullback–Leibler divergence is no longer abstract: it is the extra cost in bits of describing pp data with the qq code (the “excess surprise” interpretation from lesson 2, now with an operational proof). With p=(12,14,18,18)p = (\tfrac12, \tfrac14, \tfrac18, \tfrac18) and an engineer assuming uniform qq: H(p,q)=2H(p, q) = 2, H⁡(p)=1.75\Ent(p) = 1.75, KL⁡(p ∥ q)=0.25\KL(p\,\|\,q) = 0.25. If qq reverses pp, (18,18,14,12)(\tfrac18, \tfrac18, \tfrac14, \tfrac12), the excess is 0.8750.875 bits, 50 %50\,\% more. And if qq assigns mass 0.010.01 to the most frequent symbol and splits the rest equally, q=(0.01,0.33,0.33,0.33)q = (0.01, 0.33, 0.33, 0.33), we get KL⁡=2.37\KL = 2.37: you pay almost 7 bits each time a symbol that occurs half the time appears.

InteractivePaying for the wrong model
Source pp and model qq over 4 symbols
0.00.250.50.751.00.500.25aℓq = 2.00ℓp = 1.000.250.25bℓq = 2.00ℓp = 2.000.130.25cℓq = 2.00ℓp = 3.000.130.25dℓq = 2.00ℓp = 3.00pq
Mean length per symbol when describing pp data with the qq code (bits)
01234H(p)
Cost with the correct modelExcess from using model qCost with integer-length words
H⁡(p)\Ent(p) (correct model)1.750 bits
KL⁡(p ∥ q)\KL(p\,\|\,q) (excess)0.250 bits
H(p,q)=H⁡(p)+KL⁡(p ∥ q)H(p, q) = \Ent(p) + \KL(p\,\|\,q)2.000 bits
With integer lengths ⌈−log⁡q⌉\lceil -\log q \rceil2.000 bits
You pay H(p,q)=1.750+0.250=2.000H(p, q) = 1.750 + 0.250 = 2.000 bits per symbol. The extra 0.250 is the price of using ideal qq lengths instead of pp lengths.
Top: source pp (blue) and model qq (orange) over four symbols; below each symbol, ideal code lengths ℓq=−log⁡2q\ell_q = -\log_2 q for qq and pp. Bottom: mean length when describing pp data with the qq code, stacked as entropy (blue) plus divergence (red). Align qq with pp until red disappears. Then lower qq for a frequent symbol toward 0 and watch it shoot up; compare lowering qq for a rare one. Does overestimating a frequent symbol cost the same as underestimating it? The point marks cost with integer lengths ⌈−log⁡q⌉\lceil -\log q \rceil and the bracket shows the length-1 interval beginning at H(p,q)H(p, q): the point always falls inside.

Three readings of the same quantity come together here and accompany the rest of the module:

  • Compression. KL⁡(p ∥ q)\KL(p\,\|\,q) is what you lose by using a code fitted to qq. If qq forbids a symbol that occurs (infinite length), you pay ∞\infty: the code has no word.
  • Learning. If qθq_\theta is a language model and pp the real text, mean cross-entropy loss measured in bits is H(p,qθ)H(p, q_\theta), the mean length of the code a model-based compressor would build. Training shortens that code. The minimum possible, H⁡(p)\Ent(p), is language’s irreducible noise (lesson 6).
  • Statistics. The same number is mean evidence per observation for pp against qq (lesson 2), so a model that makes few errors is one that costs little to describe.

Huffman’s limits and the value of blocks

Huffman is optimal among symbol-by-symbol codes with known distribution. Outside those assumptions it makes no promise, and both assumptions have costs.

Symbol by symbol. Each symbol uses an integer number of bits, so it can never cost less than one. For a binary source the code is {0,1}\{0, 1\} for any pp and L=1L = 1 always, however tiny entropy h2(p)h_2(p) is. With p=0.95p = 0.95, h2=0.286h_2 = 0.286: the code uses 3.53.5 times the necessary bits. In general (Gallager, 1978), Huffman redundancy L−H⁡(p)L - \Ent(p) is at most pmax⁡+0.086p_{\max} + 0.086, where pmax⁡p_{\max} is the most frequent symbol’s probability: it is worse the more biased the source, precisely when compression seemed most promising.

Blocks. The remedy is the block bound above: applying Huffman to the alphabet Xk\mathcal{X}^k of kk-symbol blocks lowers the excess per symbol to at most 1/k1/k. But alphabet size grows as ∣X∣k\abs{\mathcal{X}}^k: a binary source with k=10k = 10 already needs a table of 10241024 words, and with 256 symbols (bytes) and k=4k = 4, over four billion. The figure lets you explore the tradeoff.

InteractiveHuffman versus blocks
Bits per symbol for Huffman blocks of k symbols
0.00.250.50.751.0123456789101112block size kuncompressed (1 bit)entropy h₂(p)cota h₂ + 1/k0.574
Code table for blocks of 2 symbols
aa0.9020ab0.048100ba0.04811bb0.0025101
0.950
2
Vertical axis
Huffman Lk/kL_k/k0.574 bits
Entropy h2(p)h_2(p)0.286 bits
Excess Lk/k−h2L_k/k - h_20.287 bits
Codewords in table4
Smallest kk with Lk/k≤1.1 h2L_k/k \le 1.1\,h_27
Blocks of 2: Lk/k=0.574L_k/k = 0.574 versus h2=0.286h_2 = 0.286. Excess 0.287 respects bound 1/k = 0.500; the table now has 4 codewords.
Binary source with P(a)=pP(a) = p and block size kk. Blue is length per symbol of Huffman on the 2k2^k blocks; the dashed line is entropy h2(p)h_2(p); points on the dotted orange line show bound h2+1/kh_2 + 1/k. With p=0.95p = 0.95 and k=1k = 1 the code spends 1 bit where 0.2860.286 suffices. Raise kk and observe that improvement is quick initially and then slow. With p=0.9p = 0.9, does blue always fall? Switch to the excess axis (logarithmic scale): does it decrease like 1/k1/k? For p=0.99p = 0.99, does k≤12k \le 12 get within 10 %10\,\% of entropy? How many words does the table already have?

Three observations are clear in the figure. First: with p=0.95p = 0.95, length per symbol is 11, 0.5740.574, 0.4330.433, 0.3670.367 for k=1,2,3,4k = 1, 2, 3, 4 and 0.2920.292 for k=10k = 10, against h2=0.286h_2 = 0.286. Improvement is enormous at first and slow afterward. Second: excess does not decrease monotonically. Bound 1/k1/k guarantees only a ceiling; what happens inside depends on how block masses align with powers of 12\tfrac12: with p=0.9p = 0.9 excess is 0.01120.0112 at k=5k = 5, falls to 0.00120.0012 at k=6k = 6 and rises to 0.00530.0053 at k=7k = 7. With p=0.95p = 0.95 length falls to 0.28740.2874 at k=12k = 12 (excess 0.00110.0011), then rises at k=13k = 13 (0.28780.2878) and to k=16k = 16 (0.28920.2892); eventually it tends to h2h_2 because excess stays below 1/k1/k, but not monotonically. Third: convergence is slow for a highly biased source. With p=0.99p = 0.99 and k=12k = 12 (a table of 40964096 words), 0.1220.122 bits per symbol remain versus h2=0.081h_2 = 0.081, 51 %51\,\% more; exceeding k=16k = 16 is needed to get below 30 %30\,\%.

There is also a cost hidden by length theory: the receiver must know the code. If the table is sent, its header counts and in a small file may exceed the saving; if adaptively estimated, the tree must stay updated. Arithmetic coding (lesson 7) solves both at once: it treats the whole sequence as one symbol, without a block table or per-symbol rounding, with total excess O(1)\bigO(1) bits over the whole sequence (for model qq, KL⁡(p ∥ q)\KL(p\,\|\,q) per symbol plus a constant). Thus modern compressors with a next-symbol prediction model, whether a low-order context or transformer, use arithmetic coding rather than Huffman. Huffman remains standard where speed and simplicity dominate: it is the last stage of DEFLATE, JPEG and many other formats.

Implementation from scratch

First, Huffman with heapq (a binary heap, like the one in the algorithms lesson). Queue entries are (peso, orden, árbol) tuples: the second element breaks ties in creation order (leaves created earlier emerge before equal-weight internal nodes) and prevents Python comparing two trees. The code checks the lesson’s proofs: Kraft equality, the redundancy identity, bit-by-bit decoding and agreement between measurements on a sample of 10410^4 symbols and theory.

[ ]Huffman with heapq, Kraft and the redundancy identityBrowser
import heapq, math
import numpy as np

def huffman(pesos):
    """pesos: dict símbolo -> peso. Devuelve dict símbolo -> palabra (cadena de ceros y unos)."""
    if len(pesos) == 1:
        return {s: "0" for s in pesos}
    # entradas (peso, orden de creación, árbol); un árbol es un símbolo (hoja) o una pareja (izq, der)
    cola = [(w, i, s) for i, (s, w) in enumerate(pesos.items())]
    heapq.heapify(cola)
    creados = len(cola)
    while len(cola) > 1:
        w1, _, a = heapq.heappop(cola)          # el más ligero va a la izquierda (bit 0)
        w2, _, b = heapq.heappop(cola)
        heapq.heappush(cola, (w1 + w2, creados, (a, b)))
        creados += 1
    codigo = {}
    def recorre(arbol, prefijo):
        if isinstance(arbol, tuple):
            recorre(arbol[0], prefijo + "0")
            recorre(arbol[1], prefijo + "1")
        else:
            codigo[arbol] = prefijo
    recorre(cola[0][2], "")
    return codigo

def longitud_media(p, codigo):
    return sum(p[s] * len(codigo[s]) for s in p)

def entropia(p):
    return -sum(x * math.log2(x) for x in p.values() if x > 0)

p = {"a": 0.4, "b": 0.3, "c": 0.2, "d": 0.1}
codigo = huffman(p)
L, H = longitud_media(p, codigo), entropia(p)
print("código de Huffman:", dict(sorted(codigo.items())))
print(f"L = {L:.4f}   H = {H:.4f}   L - H = {L - H:.4f}")

# Kraft con igualdad (el árbol de Huffman siempre es lleno)
S = sum(2.0 ** -len(w) for w in codigo.values())
print("suma de Kraft =", S)

# identidad de la redundancia: L - H = D(p || r) + log2(1/S), con r = 2^-l / S
r = {s: 2.0 ** -len(codigo[s]) / S for s in p}
D = sum(p[s] * math.log2(p[s] / r[s]) for s in p)
print(f"D(p||r) + log2(1/S) = {D + math.log2(1 / S):.4f}")

# código de Shannon: l = ceil(-log2 p)
ls = {s: math.ceil(-math.log2(p[s])) for s in p}
Ss = sum(2.0 ** -l for l in ls.values())
Ls = sum(p[s] * ls[s] for s in p)
Dr = sum(p[s] * math.log2(p[s] / (2.0 ** -ls[s] / Ss)) for s in p)
print(f"Shannon: longitudes {ls}, suma de Kraft {Ss:.4f}, L = {Ls:.4f}  (exceso {Ls - H:.4f} = {Dr:.4f} + {math.log2(1 / Ss):.4f})")

# codificar y decodificar bit a bit
def codifica(texto, codigo):
    return "".join(codigo[s] for s in texto)

def decodifica(bits, codigo):
    inverso = {w: s for s, w in codigo.items()}
    salida, actual = [], ""
    for b in bits:
        actual += b
        if actual in inverso:           # coincide con una palabra: emitir y empezar de nuevo (instantáneo)
            salida.append(inverso[actual])
            actual = ""
    assert actual == "", "bits sobrantes: el flujo estaba truncado"
    return "".join(salida)

rng = np.random.default_rng(0)
muestra = "".join(rng.choice(list(p), size=10_000, p=list(p.values())))
bits = codifica(muestra, codigo)
assert decodifica(bits, codigo) == muestra
print(f"10 000 símbolos -> {len(bits)} bits = {len(bits) / 10_000:.4f} bits por símbolo (teoría {L})")

The code reproduces the motivation’s figures. The Kraft sum is exactly 1, the redundancy identity matches excess 0.05360.0536, and the Shannon code with S=0.6875S = 0.6875 wastes almost all excess on unused leaves. Decoding recovers the sample losslessly without any length information: only the table is needed. For the sample of 10410^4 symbols, measured length is 1.90051.9005 bits per symbol, versus theoretical 1.91.9.

The second piece is what a real compressor needs: (i) do not transmit the tree, only lengths, and reconstruct words with the same rule as the Kraft proof (the canonical code: sort symbols by length and, within equal lengths, by symbol, and assign each the next binary number); (ii) pack bits into bytes, with padding; and (iii) measure total size, including the header. This is exactly what DEFLATE and JPEG do: the header describes lengths, not words.

[ ]Canonical code, bit packing and actual size versus entropyBrowser
import contextlib, difflib, inspect, io, math
from collections import Counter

def codigo_canonico(longitudes):
    """Palabras canónicas a partir de las longitudes (la construcción de la demostración de Kraft)."""
    orden = sorted(longitudes, key=lambda s: (longitudes[s], s))
    codigo, c, anterior = {}, 0, 0
    for s in orden:
        l = longitudes[s]
        c <<= (l - anterior)              # pasa el acumulado a la escala de l bits
        assert c < (1 << l), "las longitudes violan Kraft"
        codigo[s] = format(c, f"0{l}b")
        c += 1                            # el siguiente nodo libre a la derecha
        anterior = l
    return codigo

def comprime(datos):
    """datos: bytes. Devuelve (fichero, bits del cuerpo). Formato: n, [símbolo, longitud] * n, relleno, cuerpo."""
    frec = Counter(datos)
    longitudes = {s: len(w) for s, w in huffman(dict(frec)).items()}
    codigo = codigo_canonico(longitudes)
    bits = "".join(codigo[b] for b in datos)
    relleno = (-len(bits)) % 8
    cuerpo = bytes(int((bits + "0" * relleno)[i:i + 8], 2) for i in range(0, len(bits) + relleno, 8))
    cabecera = bytes([len(longitudes) - 1])           # 1 byte: número de símbolos - 1 (hasta 256)
    for s in sorted(longitudes, key=lambda s: (longitudes[s], s)):
        cabecera += bytes([s, longitudes[s]])         # 2 bytes por símbolo
    return cabecera + bytes([relleno]) + cuerpo, len(bits)

def descomprime(fichero, n):
    k = fichero[0] + 1
    longitudes = {fichero[1 + 2 * i]: fichero[2 + 2 * i] for i in range(k)}
    pos = 1 + 2 * k
    relleno, cuerpo = fichero[pos], fichero[pos + 1:]
    bits = "".join(format(b, "08b") for b in cuerpo)
    bits = bits[:len(bits) - relleno] if relleno else bits
    inverso = {w: s for s, w in codigo_canonico(longitudes).items()}
    salida, actual = bytearray(), ""
    for b in bits:
        actual += b
        if actual in inverso:
            salida.append(inverso[actual]); actual = ""
    return bytes(salida)

def entropia_bytes(datos):
    n = len(datos)
    return -sum(c / n * math.log2(c / n) for c in Counter(datos).values())

with contextlib.redirect_stdout(io.StringIO()):      # `import this` imprime el Zen de Python: lo silenciamos
    import this
zen = "".join(this.d.get(c, c) for c in this.s).encode()
largo = inspect.getsource(difflib).encode()         # unos 84 kB de texto real, determinista

for nombre, datos in [("el Zen de Python", zen), ("el código de difflib", largo)]:
    fichero, nbits = comprime(datos)
    assert descomprime(fichero, len(datos)) == datos
    H = entropia_bytes(datos)
    print(f"{nombre}: {len(datos)} bytes")
    print(f"   entropía de orden 0: {H:.3f} bits/símbolo -> cota {H * len(datos) / 8:.0f} bytes")
    print(f"   Huffman: cuerpo {nbits / len(datos):.3f} bits/símbolo = {math.ceil(nbits / 8)} bytes; con cabecera, {len(fichero)} bytes ({8 * len(fichero) / len(datos):.3f} bits/símbolo)")

Two effects appear together. In the long text (84 kB), the body costs 4.4894.489 bits per symbol versus order-0 entropy 4.4574.457: 0.030.03 bits away, far below bound L<H⁡+1L < \Ent + 1, which is pessimistic when no symbol dominates. The header is 188188 bytes of 47 30547\,305, 0.4 %0.4\,\%. In the Zen of Python (856856 bytes), the body is 484484 bytes and header 9292: 16 %16\,\% of the file, so the total (5.385.38 bits per symbol) is almost one bit above order-0 entropy (4.4854.485). This is the table-transmission cost warned about above. Without the header the decompressor does not know which code was used, so real formats spend effort describing the tree in few bytes (DEFLATE encodes lengths themselves with another Huffman code).

Finally, the block experiment, measured rather than just calculated: Huffman on the block alphabet of a biased binary source, and a real sequence of 2⋅1042 \cdot 10^4 symbols encoded with k=4k = 4.

[ ]Block Huffman: theory and measurement on a real sequenceBrowser
import math
from itertools import product
import numpy as np

def h2(p):
    return -p * math.log2(p) - (1 - p) * math.log2(1 - p)

def huffman_bloques(p, k):
    """Huffman sobre los 2^k bloques de una fuente binaria con P(a) = p. Devuelve (código, probabilidades)."""
    probs = {}
    for bloque in product("ab", repeat=k):
        nb = bloque.count("b")
        probs["".join(bloque)] = p ** (k - nb) * (1 - p) ** nb
    return huffman(probs), probs

p = 0.95
print(f"h2({p}) = {h2(p):.4f} bits por símbolo")
for k in range(1, 9):
    codigo, probs = huffman_bloques(p, k)
    L = sum(probs[b] * len(codigo[b]) for b in probs)
    print(f"k = {k}: L_k/k = {L / k:.4f}   exceso = {L / k - h2(p):.4f}   cota 1/k = {1 / k:.4f}   palabras = {len(codigo)}")

# medido: 20 000 símbolos reales codificados por bloques de 4
rng = np.random.default_rng(0)
seq = "".join(rng.choice(["a", "b"], size=20_000, p=[p, 1 - p]))
codigo, _ = huffman_bloques(p, 4)
bits = sum(len(codigo[seq[i:i + 4]]) for i in range(0, len(seq), 4))
print(f"\nsecuencia de {len(seq)} símbolos, bloques de 4: {bits / len(seq):.4f} bits por símbolo (sin bloques: 1.0000)")

The table matches the preceding figure. The measurement on a concrete sequence, 0.36650.3665 bits per symbol, is close to theory (0.36720.3672), with expected sample fluctuation. With k=4k = 4 we already go below one bit per symbol to just over a third.

The library version

In production nobody writes their own Huffman: they use zlib (DEFLATE: LZ77 followed by Huffman), bz2 (Burrows–Wheeler transform and Huffman) or lzma. What matters is what can be isolated. The standard library lets zlib use only the Huffman stage, without searching for repetitions (Z_HUFFMAN_ONLY), equivalent to the order-0 code just written. Comparing the two with the full compressor measures the value, beyond Huffman, of exploiting text structure.

[ ]Pure Huffman versus zlib, bz2 and lzmaBrowser
import bz2, lzma, zlib

def deflate_huffman(datos):
    """DEFLATE con la etapa de LZ77 desactivada: solo códigos de Huffman por bloque."""
    c = zlib.compressobj(9, zlib.DEFLATED, -15, 9, zlib.Z_HUFFMAN_ONLY)
    return len(c.compress(datos) + c.flush())

H = entropia_bytes(largo)
print(f"Texto de {len(largo)} bytes; entropía de orden 0 = {H:.3f} bits/símbolo -> cota {H * len(largo) / 8:.0f} bytes\n")
resultados = [
    ("Huffman propio (cabecera incluida)", len(comprime(largo)[0])),
    ("zlib solo Huffman (Z_HUFFMAN_ONLY)", deflate_huffman(largo)),
    ("zlib completo (LZ77 + Huffman)", len(zlib.compress(largo, 9))),
    ("bz2", len(bz2.compress(largo, 9))),
    ("lzma", len(lzma.compress(largo))),
]
for nombre, tam in resultados:
    print(f"{nombre:38s} {tam:7d} bytes   {8 * tam / len(largo):.3f} bits/símbolo")

The custom Huffman and zlib Huffman stay close to the order-0 bound, as expected: the same kind of code applied to the same frequencies (47 30547\,305 and 47 03847\,038 bytes versus a bound of 46 78646\,786). The 267267-byte difference mainly comes from DEFLATE describing its table with fewer bytes and adapting a code to each block. The other compressors go well below order-0 entropy: full zlib gives 2.212.21 bits per symbol, and bz2 and lzma 2.052.05, less than half of 4.464.46. They violate no theorem: bound L≥H⁡(p)L \ge \Ent(p) applies to a code encoding each byte independently using global frequencies; a source with memory (text repeats words, code repeats structures) has a much lower entropy rate (entropy rate, lesson 4), and LZ77 and BWT exploit that memory (Lempel–Ziv coding).

Common mistakes

Exercises

NumericHuffman mean length
Calculate the Huffman code's mean length in bits per symbol for p=(0.4,0.3,0.2,0.1)p = (0.4, 0.3, 0.2, 0.1).
QuizWhich lengths fit?
For which of these length lists does a binary prefix code exist?

More than one answer may be correct.

ProofKraft with the maximum-depth tree
Prove: If ℓ1,…,ℓm\ell_1, \dots, \ell_m are the word lengths of a binary prefix code, then ∑i=1m2−ℓi≤1\sum_{i=1}^{m} 2^{-\ell_i} \le 1.
0
Let ℓmax⁡=max⁡iℓi\ell_{\max} = \max_i \ell_i and let T\mathcal{T} be the full binary tree of depth ℓmax⁡\ell_{\max}.

Step 1 of 3. How many leaves of T\mathcal{T} descend from word wiw_i, at depth ℓi\ell_i?

NumericThe Shannon code
Calculate mean length of the Shannon code (lengths ⌈−log⁡2pi⌉\lceil -\log_2 p_i \rceil) for p=(0.4,0.3,0.2,0.1)p = (0.4, 0.3, 0.2, 0.1).
NumericExtra bits from the model
Source p=(14,14,12)p = (\tfrac14, \tfrac14, \tfrac12) is encoded with ideal lengths for q=(12,14,14)q = (\tfrac12, \tfrac14, \tfrac14). How many extra bits per symbol are paid relative to the optimum?
NumericAssuming uniformity
A source over 3 symbols has p=(12,14,14)p = (\tfrac12, \tfrac14, \tfrac14) and a code is designed for uniform qq (ideal lengths log⁡23\log_2 3). How many extra bits per symbol are paid?
NumericTwo-symbol blocks
A binary source has P(a)=0.9P(a) = 0.9 and P(b)=0.1P(b) = 0.1. Huffman is applied to blocks of k=2k = 2 symbols (aa, ab, ba, bb). How many bits per symbol does the resulting code spend?
QuizWhat Huffman guarantees
Which statements about the Huffman code are true?

More than one answer may be correct.

ProofHuffman is optimal
Prove: The Huffman code minimizes mean length among binary prefix codes for p=(p1≥⋯≥pn>0)p = (p_1 \ge \dots \ge p_n > 0).
0
Induction on nn. For n=2n = 2 the only code is {0,1}\{0, 1\}. Let p′p' be the n−1n - 1-symbol distribution obtained by merging n−1n - 1 and nn, and L∗L^* the optimal mean length.

Step 1 of 3. There is an optimal code where the two least probable symbols are siblings at maximum depth. What exchange justifies this?

CodeHuffman lengths
Implement huffman_longitudes(p), which receives a list of positive probabilities (or weights) and returns the list of Huffman codeword lengths in the same order as the input. For a single symbol return [0]. Tests check that the Kraft sum is 1, mean length matches exhaustive search on small alphabets, and input order is respected.
import heapq

def huffman_longitudes(p):
  """Longitudes del código de Huffman para los pesos p, en el orden de la entrada."""
  n = len(p)
  # tu código: una cola de prioridad con (peso, desempate, índices de los símbolos del árbol)
  return [0] * n
Shift+Enter to run

Summary

Key idea
A prefix code is a tree, whose budget is set by Kraft’s inequality: ∑2−ℓi≤1\sum 2^{-\ell_i} \le 1. Ideal lengths are surprise −log⁡p-\log p, the optimal mean length of a symbol-by-symbol code satisfies H⁡(p)≤L∗<H⁡(p)+1\Ent(p) \le L^* < \Ent(p) + 1, Huffman achieves it, and using the wrong model costs exactly KL⁡(p ∥ q)\KL(p\,\|\,q) bits per symbol.
  • Codes. Nonsingular, UD and prefix are nested classes. Prefix codes decode on the fly and are trees whose words are leaves.
  • Kraft–McMillan. A prefix code with lengths ℓi\ell_i exists if and only if ∑i2−ℓi≤1\sum_i 2^{-\ell_i} \le 1 (proof with the depth-ℓmax⁡\ell_{\max} tree and canonical construction), and UD codes satisfy the same condition, so add nothing new.
  • Redundancy identity. L−H⁡(p)=KL⁡(p ∥ r)+log⁡(1/S)L - \Ent(p) = \KL(p\,\|\,r) + \log(1/S), with r∝2−ℓr \propto 2^{-\ell}. It gives L≥H⁡(p)L \ge \Ent(p), equality only for dyadic pp and, with ℓ=⌈−log⁡p⌉\ell = \lceil -\log p \rceil, bound L<H⁡(p)+1L < \Ent(p) + 1. With kk-symbol blocks, excess per symbol falls below 1/k1/k.
  • Huffman. Repeatedly merging the two lightest nodes gives an optimal code, by an exchange lemma and a reduction lemma. Mean length is the sum of internal-node weights. Cost O(nlog⁡n)\bigO(n \log n) with a heap.
  • Wrong model. Lengths −log⁡q-\log q with data from pp cost H⁡(p)+KL⁡(p ∥ q)=H(p,q)\Ent(p) + \KL(p\,\|\,q) = H(p, q): cross entropy is a code length and divergence its extra cost.
  • Limits. A symbol-by-symbol code never goes below one bit per symbol, and Huffman loses nearly one bit with highly biased sources. Blocks fix this at the cost of an exponential table, and arithmetic coding (lesson 7) fixes it without a table.
  • Practice. A real compressor sends lengths, not trees (canonical codes), and the header counts. zlib with Z_HUFFMAN_ONLY isolates DEFLATE’s Huffman stage.