Sub topic 3
Prefix-Free Codes and Unambiguous Decoding
This chapter assumes you can read binary strings, write basic Python functions, and follow the earlier chapters' idea that frequent symbols should get shorter codes. Variable-length codes save bits, but they create a new problem. Once codewords have different lengths, nothing in the bitstream marks where one codeword ends and the next begins. This chapter covers how to rule out that ambiguity, how to test a code for it, and why the rule Huffman coding follows costs no compression.
The Ambiguity Problem
A fixed-length code with 8 bits per symbol never has this problem. The decoder cuts the stream every 8 bits. A variable-length code gives up those fixed boundaries, and a careless choice of codewords lets one bitstream mean more than one message.
Take this code for three symbols:
| Symbol | Codeword |
|---|---|
| a | 0 |
| b | 01 |
| c | 10 |
Encode the message ac and you get 0 + 10 = 010. Encode ba and you get 01 + 0 = 010. Both messages produce the same bits, so a decoder that receives 010 has no way to know which one was sent. Every codeword here is distinct, yet the code cannot be used for compression.
The fault is that a = 0 is the start of b = 01. After reading a 0, the decoder cannot tell whether it has a complete a or the first half of a b.
The Prefix-Free Rule
A prefix-free code (often just called a prefix code) is a code in which no codeword is a prefix of any other codeword. "Prefix" here means the first bits of a string: 01 is a prefix of 0110, and every string is trivially a prefix of itself, which is why the rule only compares different codewords.
Change the code above to a = 0, b = 10, c = 11. Now a is the only codeword that starts with 0, and the two codewords that start with 1 differ in their second bit. Decoding becomes mechanical:
- Read bits one at a time into a buffer.
- When the buffer matches a codeword, output that symbol and clear the buffer.
- Repeat until the stream ends.
Because no codeword extends another, the first match is the only possible match, so the decoder never backtracks. This property has a name, instantaneous decoding: each symbol is known the moment its last bit arrives, with no lookahead.
The next chapter shows that a prefix-free code is the same thing as a binary tree with symbols only at the leaves. For now the string rule is enough.
Demonstrating Ambiguity in Code
The function below lists every way a bitstream can be split into codewords. For a prefix-free code it always returns at most one message. For the broken code it returns several.
def all_decodings(bits, codes):
"""Return every message whose encoding under `codes` equals `bits`."""
if bits == "":
return [""]
results = []
for sym, code in codes.items():
if bits.startswith(code):
for rest in all_decodings(bits[len(code):], codes):
results.append(sym + rest)
return results
ambiguous = {"a": "0", "b": "01", "c": "10"}
prefix_free = {"a": "0", "b": "10", "c": "11"}
print(all_decodings("010", ambiguous)) # ['ac', 'ba']
print(all_decodings("0100", ambiguous)) # ['aca', 'baa']
print(all_decodings("01011", prefix_free)) # ['abc']This search takes exponential time in the worst case. Its only purpose here is to show the ambiguity. A real decoder for a prefix-free code never has to search.
Testing Whether a Code Is Prefix-Free
Comparing every pair of codewords works, but it takes O(n²) comparisons for n codewords. Sorting gives a faster test. If codeword p is a prefix of codeword q, then every string that sorts between them also starts with p. So p must be a prefix of the codeword that comes right after it in sorted order, and you only need to check neighbours.
def is_prefix_free(codes):
"""True if no codeword in `codes` (a dict symbol -> bit string) is a prefix of another."""
words = sorted(codes.values())
for i in range(len(words) - 1):
if words[i + 1].startswith(words[i]):
return False
return True
print(is_prefix_free({"a": "0", "b": "01", "c": "10"})) # False
print(is_prefix_free({"a": "0", "b": "10", "c": "11"})) # True
print(is_prefix_free({"a": "00", "b": "01", "c": "10", "d": "11"})) # True
print(is_prefix_free({"a": "1", "b": "1"})) # FalseThe last case matters. Two symbols that share one codeword fail the test, because startswith is true for equal strings. That is the behaviour you want, since equal codewords can never be decoded.
Uniquely Decodable Is Wider Than Prefix-Free
A code is uniquely decodable if every bitstream has at most one parse. Prefix-free codes are uniquely decodable, but some uniquely decodable codes are not prefix-free. Here is one:
| Symbol | Codeword |
|---|---|
| a | 0 |
| b | 01 |
| c | 011 |
Here 0 is a prefix of 01, and 01 is a prefix of 011, so the code is not prefix-free. It still decodes uniquely, because every codeword starts with 0 and contains exactly one 0. Each 0 therefore marks the start of a new codeword. The cost is delay. After reading 0, the decoder cannot output anything until it sees the next 0 or the end of the stream, because it needs to know how many 1s follow.
| Class of code | Every stream has at most one parse | Decoder can emit each symbol without lookahead |
|---|---|---|
| Ambiguous (e.g. 0, 01, 10) | No | No |
| Uniquely decodable only (e.g. 0, 01, 011) | Yes | No |
| Prefix-free (e.g. 0, 10, 11) | Yes | Yes |
If uniquely decodable codes are the larger family, you might expect one of them to compress better than the best prefix-free code. None does, and the reason is the Kraft inequality.
The Kraft Inequality
For a binary code with codeword lengths l₁, l₂, …, lₙ, the Kraft inequality is:
sum over i of 2^(−lᵢ) ≤ 1
It has two parts:
- Kraft: a prefix-free code with lengths l₁…lₙ exists if and only if the lengths satisfy the inequality.
- McMillan: every uniquely decodable code also satisfies it.
Taken together, these mean that any lengths a uniquely decodable code can achieve, some prefix-free code can also achieve. Average code length depends only on the lengths, so limiting yourself to prefix-free codes loses nothing. This is why Huffman coding, DEFLATE, and JPEG all use prefix codes and never consider the larger family.
You can read the inequality as a budget. A codeword of length l uses up 2^(−l) of the total, because it rules out every longer string that starts with it. Short codewords are expensive. One codeword of length 1 uses half the budget.
from fractions import Fraction
def kraft_sum(lengths):
return sum(Fraction(1, 2 ** l) for l in lengths)
for name, lengths in [
("0, 10, 11", [1, 2, 2]),
("0, 01, 10 (ambiguous)", [1, 2, 2]),
("0, 01, 011 (uniquely decodable)", [1, 2, 3]),
("lengths 1, 1, 2", [1, 1, 2]),
("lengths 2, 2, 3", [2, 2, 3]),
]:
s = kraft_sum(lengths)
print(f"{name:35} sum = {s} feasible = {s <= 1}")The output shows three points that are easy to get wrong:
- The ambiguous code
0, 01, 10has Kraft sum exactly 1. Passing the inequality says that some prefix code with those lengths exists (here0, 10, 11). It does not say that this code is prefix-free. You still needis_prefix_freeto check a particular code. - Lengths 1, 1, 2 sum to 5/4, so no uniquely decodable code has them. Two 1-bit codewords use the whole budget, and nothing is left for a third symbol.
- Lengths 2, 2, 3 sum to 5/8. A sum below 1 means the code wastes space: at least one codeword could be made shorter without breaking the prefix property. Huffman codes for two or more symbols always reach a sum of exactly 1.
Common Errors
- Checking only distinctness. Distinct codewords are necessary but far from sufficient, as
0, 01, 10shows. - Treating Kraft as a test of a specific code. The inequality is about lengths. Two codes with the same lengths can differ in whether they are prefix-free.
- Adding separators. Putting a marker bit or byte between codewords "fixes" ambiguity but spends bits on every symbol, which undoes the compression. A prefix code needs no separators.
- Greedy decoding of a non-prefix code. Matching the shortest codeword first decodes a prefix code correctly. On a code like
0, 01, 011, it outputsatoo early and gets the rest of the message wrong.
Exercises
Exercise
Is the code {a: 1, b: 01, c: 001, d: 000} prefix-free? What is its Kraft sum?
Show answer
Yes. Sorted, the codewords are 000, 001, 01, 1, and no codeword is a prefix of the one after it. The Kraft sum is 1/2 + 1/4 + 1/8 + 1/8 = 1, so no codeword can be shortened.
Exercise
Under the code {a: 0, b: 01, c: 10}, find a bitstream of length 4 with at least two decodings, and list them.
Show answer
0100 works: it splits as 0|10|0 = "aca" and as 01|0|0 = "baa". Running all_decodings("0100", ambiguous) returns ['aca', 'baa'].
Exercise
Can a uniquely decodable binary code for four symbols have lengths 1, 2, 2, 3? Explain using the Kraft inequality.
Show answer
No. The sum is 1/2 + 1/4 + 1/4 + 1/8 = 9/8, which is greater than 1. By McMillan's theorem, no uniquely decodable code has these lengths, prefix-free or not.
Exercise
Why does isprefixfree only need to compare neighbouring codewords after sorting?
Show answer
If p is a prefix of q, every string that sorts between p and q also begins with p. So p is a prefix of the codeword right after it in sorted order, and checking neighbours finds every violation.