Sub topic 3
Prefix-Free Codes and Unambiguous Decoding
This chapter assumes you know binary strings, can read basic Python (string slicing, recursion, dictionaries), and have seen the earlier chapters' point that variable-length codes save bits by giving frequent symbols shorter patterns.
Variable-length codes raise a new problem. A fixed-length code tells the decoder where each symbol ends: every 8 bits. With variable-length codes there are no separators in the bitstream, so the code itself must make the boundaries clear.
When Decoding Goes Wrong
Take this code:
| Symbol | Code |
|---|---|
| a | 0 |
| b | 01 |
| c | 1 |
Encode b and you get 01. Encode ac and you also get 01. A decoder that receives 01 cannot tell which message was sent. The code saves bits but loses information, which makes it useless.
The cause is that 0 (the code for a) is also the start of 01 (the code for b). After reading a 0, the decoder cannot know whether the symbol is finished.
The Prefix-Free Rule
A code is prefix-free (often just called a prefix code) when no codeword is a prefix of any other codeword. Compare:
| Symbol | Ambiguous code | Prefix-free code |
|---|---|---|
| a | 0 | 0 |
| b | 01 | 10 |
| c | 1 | 11 |
In the prefix-free version, once the bits read so far match a codeword, no longer codeword can begin with those bits. The decoder can emit the symbol at once and start fresh, with no lookahead and no backtracking. This property is called instantaneous decoding.
Checking It in Code
The program below counts every way a bitstring can be parsed and tests whether a code is prefix-free. The test sorts the codewords first. After sorting, if any codeword is a prefix of another, it is also a prefix of the codeword right after it, so checking neighbours is enough.
def parses(bits, codes):
"""Return every message whose encoding is exactly `bits`."""
if not bits:
return [""]
results = []
for sym, code in codes.items():
if bits.startswith(code):
for rest in parses(bits[len(code):], codes):
results.append(sym + rest)
return results
def is_prefix_free(codes):
words = sorted(codes.values())
return all(not words[i + 1].startswith(words[i])
for i in range(len(words) - 1))
ambiguous = {"a": "0", "b": "01", "c": "1"}
prefix_free = {"a": "0", "b": "10", "c": "11"}
print(is_prefix_free(ambiguous), parses("01", ambiguous))
# False ['ac', 'b']
print(is_prefix_free(prefix_free), parses("01011", prefix_free))
# True ['abc']Common Mistakes
- Checking only distinctness. Codes like
0,01,1are all different, but distinct codewords do not guarantee unambiguous decoding. - Assuming short codes are always available. Prefix-free codeword lengths must satisfy the Kraft inequality: the sum of 2^(−length) over all codewords is at most 1. Lengths 1, 1, 2 give 1/2 + 1/2 + 1/4 > 1, so no prefix-free code with those lengths exists.
- Thinking prefix-free is the only decodable option. The code
0,01is decodable because it is suffix-free, but the decoder must look ahead to find symbol boundaries. The McMillan theorem shows that any uniquely decodable code has lengths that a prefix-free code can also achieve, so giving up the prefix rule never saves bits.
Exercise
Is the code {a: 00, b: 01, c: 1, d: 10} prefix-free? If not, give a bitstring with two valid parses.
Show answer
No. The codeword 1 (c) is a prefix of 10 (d). The bitstring 100 can be read as d followed by an incomplete 0, but with an extra 0 appended, 1000 parses as "ca" (1, 00) or as d followed by 00 is not complete... the cleaner example is 100: wait, use 10 itself plus a: 1000 = c + 00 (a) + 0 is incomplete, so try 1001: no. The simplest is 1 0 0 with a=00: "100" = c + a (1, 00). It also starts with d (10) and leaves a single 0, which is incomplete. A complete double parse: "1000" = d + a (10, 00) and = c + a + incomplete. An exact pair is "10 00 1" versus "1 00 01": the string 10001 parses as d, a, c and as c, a, b.
Exercise
Do codeword lengths 1, 2, 3, 3 satisfy the Kraft inequality? If so, write a prefix-free code with those lengths.
Show answer
Yes: 1/2 + 1/4 + 1/8 + 1/8 = 1. One such code is 0, 10, 110, 111.