Sub topic 10
Canonical Huffman Codes
The Huffman algorithm decides how long each symbol's code is. It does not decide which bits each code uses. When the heap breaks a tie differently, or a merge puts a subtree on the left instead of the right, you get a different tree. That tree has the same code lengths, but the bit patterns differ. Canonical Huffman coding fixes this by keeping only the lengths from the tree and assigning the actual bit patterns with a fixed rule. The encoder and decoder both apply that rule, so the lengths alone are enough to rebuild the code.
This chapter assumes you can build a Huffman tree with a min-heap, encode and decode with a code table, and read Python that uses bit shifts (<<) and format.
Why the Tree's Shape Is Arbitrary
Running the earlier build_codes function on "abracadabra" gives this table:
| Symbol | Frequency | Tree code | Length |
|---|---|---|---|
| a | 5 | 0 | 1 |
| c | 1 | 100 | 3 |
| d | 1 | 101 | 3 |
| b | 2 | 110 | 3 |
| r | 2 | 111 | 3 |
At any internal node you can swap the 0 and 1 branches and the code is still optimal, because every code length stays the same. You can also give two symbols of equal length each other's codes without changing the compressed size. A tree with n internal nodes therefore has at least 2^n equally good labelings. Compression only depends on the lengths, so the specific bit patterns carry no useful information. Canonical coding picks one standard labeling from all of them.
The Canonical Assignment Rule
The rule has three steps:
- Sort the symbols by code length, shortest first. Break ties by a fixed symbol order, such as byte value.
- Give the first symbol the all-zeros code of its length.
- For each next symbol, add 1 to the previous code. If the new symbol's code is longer, shift the code left by the difference in lengths, which appends zeros.
The result has two properties that matter later:
- Within one length, codes are consecutive binary numbers in symbol order.
- Every code of length L sorts before every code of length L+1 when you compare them as bit strings. Shorter codes take the numerically smallest prefixes.
def canonical_codes(lengths):
# lengths: dict mapping symbol -> code length in bits
ordered = sorted(lengths.items(), key=lambda item: (item[1], item[0]))
codes = {}
code = 0
prev_len = ordered[0][1]
for sym, length in ordered:
code <<= (length - prev_len)
codes[sym] = format(code, "0{}b".format(length))
code += 1
prev_len = length
return codes
print(canonical_codes({"a": 1, "b": 2, "c": 3, "d": 3}))
# {'a': '0', 'b': '10', 'c': '110', 'd': '111'}
print(canonical_codes({"a": 1, "b": 3, "c": 3, "d": 3, "r": 3}))
# {'a': '0', 'b': '100', 'c': '101', 'd': '110', 'r': '111'}Here is how the second call works. Symbol a gets 0, and the counter moves to 1. The length then jumps from 1 to 3, so the counter shifts left by 2 and becomes 4 (100), which goes to b. Then c gets 5 (101), d gets 6 (110), and r gets 7 (111). Compare this with the tree code table: b moved from 110 to 100, while every length stayed the same.
Why the Result Is Still a Valid Prefix Code
Two conditions guarantee the canonical codes are prefix-free:
- Within one length, codes are distinct numbers with the same number of bits, so neither can be a prefix of the other.
- Across lengths, the next code after the last code of length L is that code plus 1, shifted left. No code of length L can be a prefix of it, because the shifted value is at least
(last + 1) · 2^k. Every extension of any length-L code lies below that value.
This relies on the lengths satisfying the Kraft inequality, the sum of 2^(−length) over all symbols being at most 1. Huffman lengths always satisfy it, and they reach exactly 1. If you pass in lengths that break it, the counter overflows its bit width. The table looks plausible but is wrong. The exercises show an example.
The Count-Based Formulation Used by DEFLATE
Real implementations rarely sort symbol by symbol. RFC 1951, the DEFLATE specification, describes the same rule using counts. First count how many symbols have each length (bl_count[L]). Then compute the first code of each length:
next_code[L] = (next_code[L-1] + bl_count[L-1]) << 1
with next_code[1] = 0. Symbols of length L, taken in symbol order, get next_code[L], next_code[L] + 1, and so on. This gives the same codes as the sorting version. It runs in time proportional to the number of symbols plus the maximum length. It also never needs a comparison sort, because the symbol alphabet (byte values 0 to 255, for example) is already in order.
Decoding Without a Tree
Canonical codes also make decoding cheaper. Codes of length L form one consecutive run of numbers, so the decoder needs only bl_count and the symbols listed in canonical order. It reads one bit at a time. At each length it checks whether the value read so far falls inside that length's run:
def canonical_decoder(lengths):
max_len = max(lengths.values())
bl_count = [0] * (max_len + 1)
for length in lengths.values():
bl_count[length] += 1
symbols = [sym for sym, _ in sorted(lengths.items(),
key=lambda item: (item[1], item[0]))]
def decode(bits):
out = []
code = first = index = length = 0
for b in bits:
code |= int(b)
length += 1
if length > max_len:
raise ValueError("invalid code in bitstream")
count = bl_count[length]
if code - first < count:
out.append(symbols[index + code - first])
code = first = index = length = 0
else:
index += count
first = (first + count) << 1
code <<= 1
if length:
raise ValueError("bitstream ended mid-code")
return "".join(out)
return decode
lengths = {"a": 1, "b": 3, "c": 3, "d": 3, "r": 3}
codes = canonical_codes(lengths)
bits = "".join(codes[ch] for ch in "abracadabra")
decode = canonical_decoder(lengths)
assert decode(bits) == "abracadabra"
print(bits, len(bits))The variable first holds the first canonical code of the current length, and index holds how many symbols belong to shorter lengths. If code - first is smaller than the number of codes of this length, the bits match a symbol and its position is known directly. Otherwise the decoder moves to the next length, in the same way the encoder's counter shifted. zlib's reference decoder, puff.c, uses this loop. Fast decoders go further: they build a lookup table indexed by the next N bits, which is easy to fill because each length's codes are consecutive.
Edge Cases and Conventions
| Situation | What to do |
|---|---|
| Symbol never appears | Give it length 0 and leave it out of sorting and counting. DEFLATE sends 0 for absent symbols. |
| Only one distinct symbol | Give it length 1 (code `0`), matching the special case in `build_codes`. The Kraft sum is 1/2, so the code is incomplete, and the decoder must reject the unused `1`. |
| Tie-break order | Encoder and decoder must use the same symbol order. Python sorts strings by code point, while formats specify numeric symbol values. Never rely on dictionary order. |
| Maximum length | Lengths can grow to about n − 1 bits with skewed frequencies. Formats cap them (15 bits in DEFLATE, 16 in JPEG), which a later chapter covers. |
| Bit order on the wire | Canonical rules define codes with the most significant bit first. DEFLATE packs other fields starting at the least significant bit but writes Huffman codes starting at their most significant bit, a frequent source of bugs. |
Exercise
Compute the canonical codes for the lengths {a: 2, b: 2, c: 2, d: 3, e: 3}, and confirm the Kraft sum.
Show answer
Sorted order is a, b, c (length 2), then d, e (length 3). a = 00, b = 01, c = 10. The counter becomes 3 (11) and shifts left by 1 to 6, so d = 110 and e = 111. Kraft sum: 3 × 1/4 + 2 × 1/8 = 1.
Exercise
What does canonical_codes return for {a: 1, b: 1, c: 2}, and why is it wrong?
Show answer
a = 0 and b = 1. The counter becomes 2 and shifts to 4, and format(4, "02b") gives "100", three bits for a length-2 code. The Kraft sum is 1/2 + 1/2 + 1/4 = 1.25, which is more than 1, so no prefix code with these lengths exists. A decoder must reject this input.
Exercise
Two encoders build different Huffman trees for the same file because their heaps break ties differently, but both produce the same code lengths. Will their canonical outputs match bit for bit?
Show answer
Yes. Canonical assignment depends only on the lengths and the fixed symbol order, so both produce the same code table and the same bitstream. The output can differ only if the tie-breaking changes the lengths themselves, which can happen when frequencies are equal.