Search

Search papers and lessons

Prefix-Free Code

Level 2 · 11 min read

A prefix-free code gives each symbol a bit string so that no codeword is the start of another, which lets a stream of bits be decoded left to right with no separators.

On this page

  • Colour = topic mix
  • Discrete math
  • Algorithms
  • Calculus
  • ReadReady to readNot yet

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.

SymbolCodeword
A0
B10
C110
D111
  1. Encode the message. The message is A B C D. Write the codewords one after another: 0, then 10, then 110, then 111. Check: the bit stream is 0 10 110 111, which is nine bits long with no separators.
  2. Read the first bit. The receiver reads 0. It is the codeword for A. No other codeword starts with 0, 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.
  3. Read the next bits. The receiver reads 1. No codeword is 1 alone, so it keeps reading. It reads 0, which makes 10. That matches B, and no longer codeword starts with 10, so the symbol is B. Check: the second symbol is B, and two bits were used.
  4. Read the third symbol. The receiver reads 1, then 1, which makes 11, still ambiguous. It reads 0 and has 110, which is C. Check: the third symbol is C, and three bits were used.
  5. Read the last symbol. The remaining bits are 111. That is D. Check: the output is A 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 s1,…,sns_1, \dots, s_n, and let codeword cic_i be a string of bits with length ℓi\ell_i. Write len(ci)=ℓi\mathrm{len}(c_i) = \ell_i. The code is prefix-free when no codeword is a prefix of another:

for all i≠j,ci is not a prefix of cj.\text{for all } i \neq j, \quad c_i \text{ is not a prefix of } c_j.

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 cA=0c_A = 0, cB=10c_B = 10, cC=110c_C = 110, cD=111c_D = 111. The pair cA=0c_A = 0 and cB=10c_B = 10 is fine, because 1010 does not begin with 00. The check cB=10c_B = 10 against cC=110c_C = 110 is fine, because 110110 begins with 11 and then 11, not 1010. Every pair passes, so the code is prefix-free.

Which lengths are possible: the Kraft inequality

A prefix-free code exists with lengths ℓ1,…,ℓn\ell_1, \dots, \ell_n exactly when the lengths satisfy the Kraft inequality, a fact about binary trees, where ℓi\ell_i is the depth of the leaf for symbol sis_i: the sum of the terms 2−ℓi2^{-\ell_i} over all symbols is at most 1.

∑i=1n2−ℓi≤1.\sum_{i=1}^{n} 2^{-\ell_i} \le 1.

For the example, the lengths are 1, 2, 3, 3, and

2−1+2−2+2−3+2−3=12+14+18+18=1.2^{-1} + 2^{-2} + 2^{-3} + 2^{-3} = \tfrac{1}{2} + \tfrac{1}{4} + \tfrac{1}{8} + \tfrac{1}{8} = 1.

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 12+12+14+14>1\tfrac12 + \tfrac12 + \tfrac14 + \tfrac14 > 1.

Average length

If symbol sis_i occurs with probability pip_i, the average number of bits per symbol is

L=∑i=1npi ℓi.L = \sum_{i=1}^{n} p_i \, \ell_i.

Suppose pA=0.5p_A = 0.5, pB=0.25p_B = 0.25, pC=0.125p_C = 0.125, pD=0.125p_D = 0.125. Then L=0.5⋅1+0.25⋅2+0.125⋅3+0.125⋅3=1.75L = 0.5 \cdot 1 + 0.25 \cdot 2 + 0.125 \cdot 3 + 0.125 \cdot 3 = 1.75 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

Example
Tiny: two codewords

The codewords are A = 0 and B = 10.

  1. Check the rule: 10 does not begin with 0, and 0 does not begin with 10. The code is prefix-free.
  2. Decode the stream 100. Read 1, then 0, which makes 10, so the first symbol is B.
  3. Read the next bit, 0. That is A.
  4. Output: B A.

Interpretation: the stream has three bits and two symbols, so the decoder never needed a separator.

Example
Standard: the four-symbol code

Use the code above with A = 0, B = 10, C = 110, D = 111.

  1. Encode D A B: 111 then 0 then 10, giving the stream 111 0 10, or 111010.
  2. Decode 111010. Read 1, 1, 1, which makes 111. That is D.
  3. Read 0. That is A.
  4. Read 1, 0, which makes 10. That is B.
  5. 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.

Example
Realistic: saving bits on a skewed source

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 22=42^2 = 4. The prefix-free code above averages L=1.75L = 1.75 bits.

  1. Fixed-length cost: 2 bits per report.
  2. Prefix-free average cost: 1.75 bits per report.
  3. Saving: 2−1.75=0.252 - 1.75 = 0.25 bits per report, which is 0.25/2=12.50.25 / 2 = 12.5 percent of the fixed-length cost.
  4. 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, ∑2−ℓi≤1\sum 2^{-\ell_i} \le 1, says which length sets are possible for a prefix-free code.
  • The average length L=∑piℓiL = \sum p_i \ell_i 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 LL, and Trie uses the same prefix idea to store and search strings.

Check yourself

QuestionRecall: what does it mean for codeword cic_i to be a prefix of codeword cjc_j?Show answer

It means cjc_j begins with the bits of cic_i, so cic_i is the start of cjc_j. A prefix-free code forbids this for any two different symbols. In particular, if ci=cjc_i = c_j then cic_i is a prefix of cjc_j, 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 LL?Show answer

L=0.4⋅1+0.3⋅2+0.2⋅3+0.1⋅3=0.4+0.6+0.6+0.3=1.9L = 0.4 \cdot 1 + 0.3 \cdot 2 + 0.2 \cdot 3 + 0.1 \cdot 3 = 0.4 + 0.6 + 0.6 + 0.3 = 1.9 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.

Sources