TL;DR
A prefix-free code assigns each symbol a string of bits, called its codeword, so that no codeword is the beginning of another codeword. Because of this rule, a receiver reading a stream of bits from left to right always knows where one symbol ends and the next begins. It solves the problem of sending variable-length codes without adding separators, which saves space whenever some symbols are more common than others.
Builds on: Binary Tree, Binary Numbers (Bits and Bytes) · Leads to: Huffman Coding, Trie
Where it's used
Compressed files. Lossless compression formats such as DEFLATE, which underlies ZIP and gzip, store their Huffman tables as code lengths and build prefix-free codes from them. Common byte values get short codes and rare ones get long codes, and the decoder reads the stream one code at a time.
Image and video formats. JPEG stores the quantized coefficients of each image block using variable-length prefix-free codes, so smooth regions cost few bits. The same principle appears in the entropy-coding stages of many video codecs.
Text encoding. UTF-8 stores each character in one to four bytes, and it is prefix-free: the leading bits of the first byte say how many bytes follow, so a decoder can find each character's end without looking at the next one.
Contrast with Morse code. Morse code is not prefix-free: the letter E is a single dot, and the letter I is two dots, so E is the start of I. Morse therefore needs a pause between letters to separate them.
How it works
Take four symbols, A, B, C and D, with the codewords below. Each codeword is a string of bits.
| Symbol | Codeword |
|---|---|
| A | 0 |
| B | 10 |
| C | 110 |
| D | 111 |
- Encode the message. The message is
A B C D. Write the codewords one after another:0, then10, then110, then111. Check: the bit stream is 0 10 110 111, which is nine bits long with no separators. - Read the first bit. The receiver reads
0. It is the codeword for A. No other codeword starts with0, so the receiver can be sure it is A without waiting for more bits. Check: the first symbol is A, and one bit was used. - Read the next bits. The receiver reads
1. No codeword is1alone, so it keeps reading. It reads0, which makes10. That matches B, and no longer codeword starts with10, so the symbol is B. Check: the second symbol is B, and two bits were used. - Read the third symbol. The receiver reads
1, then1, which makes11, still ambiguous. It reads0and has110, which is C. Check: the third symbol is C, and three bits were used. - Read the last symbol. The remaining bits are
111. That is D. Check: the output isA B C D, the original message, and every bit was used exactly once.
Now break the rule. Suppose the codewords are A = 0, B = 01, C = 10. The bit stream 010 can be read as A then C (0, 10) or as B then A (01, 0). The receiver cannot tell which message was sent, because 0 is the beginning of 01.
The tree view makes the rule easy to check. Put each codeword on a binary tree: a left edge is 0, a right edge is 1, and the codeword of a symbol is the path from the root to its node. If every symbol sits on a leaf, the codewords are prefix-free, because a leaf has no descendants that could be another codeword.
flowchart TD R["root"] -->|0| A["A = 0"] R -->|1| N1["node"] N1 -->|0| B["B = 10"] N1 -->|1| N2["node"] N2 -->|0| C["C = 110"] N2 -->|1| D["D = 111"]
The math
Let the symbols be , and let codeword be a string of bits with length . Write . The code is prefix-free when no codeword is a prefix of another:
In words: take any two different symbols; the first codeword is never the initial segment of the second. A codeword may equal another only if the two symbols are the same, so distinct symbols need distinct codewords too.
Checking the rule for every pair
For the example, the codewords are , , , . The pair and is fine, because does not begin with . The check against is fine, because begins with and then , not . Every pair passes, so the code is prefix-free.
Which lengths are possible: the Kraft inequality
A prefix-free code exists with lengths exactly when the lengths satisfy the Kraft inequality, a fact about binary trees, where is the depth of the leaf for symbol : the sum of the terms over all symbols is at most 1.
For the example, the lengths are 1, 2, 3, 3, and
The sum equals 1, so the tree is complete: every internal node has two children. The inequality tells you that you cannot give four symbols lengths 1, 1, 2, 2, because .
Average length
If symbol occurs with probability , the average number of bits per symbol is
Suppose , , , . Then bits per symbol. This is the same as the Entropy of that distribution, so no prefix-free code can do better for this source.
Worked examples
The codewords are A = 0 and B = 10.
- Check the rule:
10does not begin with0, and0does not begin with10. The code is prefix-free. - Decode the stream
100. Read1, then0, which makes10, so the first symbol is B. - Read the next bit,
0. That is A. - Output:
B A.
Interpretation: the stream has three bits and two symbols, so the decoder never needed a separator.
Use the code above with A = 0, B = 10, C = 110, D = 111.
- Encode
D A B:111then0then10, giving the stream111 0 10, or111010. - Decode
111010. Read1,1,1, which makes111. That is D. - Read
0. That is A. - Read
1,0, which makes10. That is B. - Output:
D A B, the original message.
Interpretation: decoding is a walk down the tree. Each bit moves to a child, and reaching a leaf gives a symbol and sends the walk back to the root.
A sensor reports one of four states, A, B, C or D, with probabilities 0.5, 0.25, 0.125 and 0.125. A fixed-length code needs 2 bits for each of the four states, since . The prefix-free code above averages bits.
- Fixed-length cost: 2 bits per report.
- Prefix-free average cost: 1.75 bits per report.
- Saving: bits per report, which is percent of the fixed-length cost.
- Interpretation: the state A occurs half the time, so giving it the one-bit codeword does most of the saving. Over a million reports the difference is 250,000 bits, about 31 kilobytes, which the sensor never has to send.
Try it: a code uses A = 0, B = 10, C = 11. Decode the stream 110100. Answer: read 11, which is C. Read 0, which is A. Read 10, which is B. Read 0, which is A. The output is C A B A.
Common mistakes and tradeoffs
It is tempting to think that prefix-free means only that all codewords are different. In fact the stronger rule forbids any codeword from being the beginning of another. A code can have distinct codewords and still be ambiguous, as with A = 0, B = 01, C = 10, where 0 starts 01.
It is tempting to think that any fixed-length code is prefix-free, which is true, and that any prefix-free code is a good compression. In fact prefix-free only guarantees that a stream can be decoded. The lengths decide how much space is saved, and a prefix-free code with poor lengths can waste many bits. An optimal choice of lengths is what Huffman Coding computes.
It is tempting to think that a prefix-free code needs no shared information. In fact the decoder must know the codeword table, so the table has to be sent, built in, or agreed in advance. The table itself costs space, which matters for short messages.
Use a prefix-free code when symbols have very different frequencies, when the message is streamed and the decoder must not wait for separators, and when the table can be shared. Avoid it when a single flipped bit must not corrupt the rest of the stream, since one error can shift every later codeword; add a checksum or error-correcting bits in that case. Also avoid it when random access into the middle of the stream is needed, or when all symbols are equally likely and a fixed-length code is just as short. Alternatives include fixed-length codes, explicit length fields, and separator characters.
History
Claude Shannon's 1948 paper "A Mathematical Theory of Communication" founded information theory, and its entropy result is the limit this lesson compares against. It showed that the average number of bits needed per symbol is limited by the entropy of the source and that codes approaching this limit exist. Shannon's construction used codewords whose lengths were set from the symbol probabilities, and those codes were prefix-free.
In 1952, David Huffman, then a graduate student at MIT, published a method that builds a prefix-free code for given probabilities and achieves the best average length among prefix-free codes. The method, now called Huffman coding, was quickly adopted because it is simple, fast and optimal in this sense.
Prefix-free codes caught on because they solve a practical problem without any extra symbols. Compressed files, image formats and communication standards all use them whenever a stream must be decoded on the fly.
Recap
- A prefix-free code assigns bit strings to symbols so that no codeword begins another, which makes left-to-right decoding unambiguous.
- Codewords can be read as root-to-leaf paths in a Binary Tree, with symbols only at leaves.
- The Kraft inequality, , says which length sets are possible for a prefix-free code.
- The average length measures compression, and it cannot go below the Entropy of the source, a quantity measured in logarithms of the probabilities.
- Read next: Huffman Coding chooses the lengths that minimise , and Trie uses the same prefix idea to store and search strings.
Check yourself
QuestionRecall: what does it mean for codeword to be a prefix of codeword ?Show answer
It means begins with the bits of , so is the start of . A prefix-free code forbids this for any two different symbols. In particular, if then is a prefix of , so distinct symbols must have distinct codewords.
QuestionComputation: a source has probabilities 0.4, 0.3, 0.2 and 0.1, with codeword lengths 1, 2, 3 and 3. What is the average length ?Show answer
bits per symbol.
QuestionWhy: why does a prefix-free code let a receiver decode without separators, while a code like A = 0, B = 01 does not?Show answer
In a prefix-free code, once the bits read so far match a codeword, no longer codeword can also match those bits, so the symbol is known at once. In A = 0, B = 01, the bit 0 matches A, but 01 could be the start of B. The receiver cannot decide between A and the longer codeword without a separator or lookahead, so the decoding is ambiguous.
QuestionApplied scenario: a system sends messages with a shared, fixed codeword table. A single bit is flipped during transmission. Why might the rest of the message be garbled even though the code is prefix-free?Show answer
Prefix-free codes guarantee unambiguous decoding for a correct stream, but a flipped bit can change the codeword that is read, so the decoder then reads the following bits from the wrong position. Since codewords have different lengths, the decoder can stay out of step with the true boundaries for a while. Prefix-free codes do not correct errors, so a system that needs robustness adds error-detecting or error-correcting bits.