Huffman’s Tree
Chapter 4 showed what a good code must look like: a tree whose leaves sit at depths close to each symbol's surprise. Here is a recipe that builds the best such tree, from the bottom up, by repeatedly pairing the two rarest things in the pile. Type a message and watch its redundancy drain away.
Suppose you have counted the letters of a message and want the shortest prefix-free code for it. You could try splitting the symbols top-down into two groups of roughly equal weight, then splitting each group again. Shannon and Robert Fano both proposed methods along those lines, and they work well, but they do not always find the best code.
David Huffman, then a graduate student at MIT, turned the problem upside down. Instead of starting from the root, start from the leaves. His method, published in 1952, is short enough to fit on an index card and is guaranteed to give the lowest possible average length among all codes that assign one codeword to each symbol.
Put every symbol in a pile with its count. Take out the two smallest, join them under a new node whose count is their sum, and put that node back. Repeat until one node remains: that is the root of the code tree.
Why the two rarest? In the best code, the two least likely symbols should get the longest codewords, and they can always be placed as twins: siblings at the very bottom of the tree, differing only in their final bit. Join them, treat the pair as a single symbol, and you are left with the same problem, one symbol smaller. Repeat, and the tree assembles itself.
The Huffman Workshop
Type anything into the box, or pick one of the sample messages. The page counts each symbol, builds the Huffman tree (press Replay merges to watch it grow one merge at a time), lists every symbol's codeword, and compares the total against plain 8-bit text, against the best fixed-length code, and against the entropy floor.
| symbol | count | share | surprise | codeword | length | bits used |
|---|
Look at the code table. Common symbols such as the space and "e" sit high in the tree with short codewords; rare ones hang at the bottom with long codewords. Compare the length column with the surprise column: Huffman's lengths follow the surprises, usually the surprise rounded up or down, but not always. In the Lopsided sample the rare "b" gets a 1-bit codeword despite a 5.9-bit surprise, because with only two symbols nothing shorter or longer is possible. Huffman does not round symbol by symbol; it picks the whole set of lengths that fills the budget of Chapter 4 at the lowest total.
What the bars always show
Whatever you type, three things stay true. The Huffman bar is never longer than the fixed-length bar. It is never shorter than the entropy floor. And it is always less than one bit per symbol above that floor (apart from the one-symbol case noted below). In symbols:
Be careful about what that H is. When the page computes an entropy from your message's own letter counts, it is the entropy of the model that says "each character is drawn independently, with these frequencies". That model ignores order completely. It is the right yardstick for a symbol-by-symbol code like Huffman's, but it is not the true information content of your message, as the next two experiments show.
Blind spot 1: whole bits only
Pick the Lopsided sample: sixty characters, almost all "a". The letter-frequency model says each character carries only about 0.12 bits. But a Huffman codeword cannot be shorter than one whole bit, so the code needs 60 bits, eight times the floor. Huffman is still doing the best that any one-codeword-per-symbol code can do; the limitation is the format.
One classic remedy is to code symbols in blocks: treat each pair, or triple, of symbols as a single super-symbol and Huffman-code those. The rounding loss of up to one bit is then shared across several symbols. Try it with a lopsided two-symbol source.
Many modern compressors take a smoother route called arithmetic coding (and its cousins), which effectively lets a symbol cost a fraction of a bit and gets within a hair of the entropy over a whole message without giant tables. Chapter 12 shows the idea as a shrinking interval.
Blind spot 2: one symbol at a time
Now pick Repetitive: "abababab…". Half the characters are "a" and half "b", so the letter-frequency model says 1 bit per character, Huffman gives 1 bit per character, and the bars agree perfectly. Yet the message is absurdly predictable: after the first letter, every next letter is certain. Its real information is close to nothing beyond "ab, repeated 28 times".
Huffman cannot see this because it codes each symbol on its own, with fixed probabilities, ignoring what came before. Patterns that live in the order of symbols, like the u after q in Chapter 3 or the repeats here, are invisible to it. Catching them needs a model with context (Chapter 12) or a compressor that spots repeats (Chapter 7).
Huffman's code is optimal among prefix codes that give each symbol its own codeword, for known symbol frequencies. It is not the best possible compressor: block coding, arithmetic coding and context models can all do better on real data.
None of this makes Huffman coding a museum piece. It is fast, simple, and still sits inside formats you use every day: the DEFLATE method used by zip, gzip and PNG files ends with a Huffman stage, and baseline JPEG images use Huffman coding as their final lossless step. Chapter 7 shows what DEFLATE does before it gets to Huffman.
Four symbols have counts A = 10, B = 5, C = 3, D = 2. How long is A's Huffman codeword?
A source sends "a" 90% of the time and "b" 10%. Its entropy is about 0.47 bits per symbol. What does a symbol-by-symbol Huffman code average?
Connections
- Large Language Models, Chapter 2: Tokenization: byte-pair encoding also builds its vocabulary by repeated merging, though it merges the most frequent neighbouring pairs to make tokens rather than building a code tree.
- Signals to Thinking Machines covers the trees and data structures that programs like this one are built from.
- Chapter 4 explains why every Huffman code is prefix-free: its codewords are the leaves of the tree you just watched grow.
What you now see
- Huffman's recipe: repeatedly merge the two least frequent nodes; the merges form the code tree, and paths from the root give the codewords.
- Common symbols end up near the root (short codewords), rare ones deep down (long codewords): lengths roughly track the surprises.
- For known frequencies, Huffman's average lies at or above the entropy and less than one bit per symbol above it.
- English text squeezes well. Random characters from a small alphabet shrink only to about log₂ (alphabet size) bits each, the same as a fixed-length code; random bytes do not shrink at all.
- Huffman is optimal only among symbol-by-symbol prefix codes: whole-bit lengths waste bits on very lopsided sources, and order-based patterns ("abab…") are invisible to it.