Information Theory CompanionInformation Theory · Companion
0 / 0

Workbench / Information Theory Companion

B1·05

Codes: Prefix Codes, Kraft's Inequality and Huffman Coding

Around chapter 5: how codes connect counting, entropy and the source coding theorem; three other ways to see them; what the chapter simplifies (Huffman is optimal only for the counts it was built from, its gap to the entropy is usually far less than a bit, and rare symbols can get very long codewords); how zlib turns codeword lengths into DEFLATE's canonical codes, checked against RFC 1951's own example; four debugging drills; and interview questions.

6 topics · ~16 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Question trees (chapter 2) = codes: a codeword is a path, a symbol a leaf.
  • Prefix property → instantaneous decoding → Kraft's inequality ∑2−l≤1 (and McMillan for every uniquely decodable code).
  • Entropy (chapter 4) → average length ≥H → equality only for powers of 12.
  • Shannon code ⌈log21p⌉ → within 1 bit → Huffman merges bottom-up → optimal, complete.
  • Canonical codes → send lengths only (DEFLATE, JPEG).
  • Limits: whole-number lengths → blocks (chapter 6), runs, arithmetic coding (chapter 6).
  • Integer codes: unary, Elias gamma, Rice → gaps, run lengths, prediction errors.
  • Fragility: a flipped bit derails decoding → checksums and error correction (chapters 8 and 9).

Explain it differently

A phone tree with short numbers for the boss. In an office directory, the people called most often get two-digit extensions and everyone else gets four. No short extension can be the start of a long one, or the switchboard would connect you too early. That's the prefix property, and choosing who gets the short numbers by how often they're called is Huffman's job.

Pouring a litre into glasses. Kraft's inequality is a litre of water poured into glasses of sizes 12,14,18,… litre: a codeword of length l is a glass of 2−l. You can't pour more than a litre. Huffman fills the glasses so that the likeliest symbols get the biggest ones, and it always uses every drop.

Merging the smallest teams. Huffman's algorithm is like organising a knock-out tournament where, at every round, the two teams with the fewest supporters play first. Little-known teams end up playing many rounds (long codewords); the favourite plays only the final (a short one). Everyone's number of games is their codeword length.

Gaps and misconceptions

What the chapter oversimplifies

1. "Huffman is optimal", for the counts it was built from. A code built from one part of a file and used on another is optimal for neither, and may be missing symbols entirely:

Python
import math
from collections import Counter
from huff import huffman_lengths
data = open("data/shakespeare.txt", "rb").read()
first, second = data[:len(data) // 2], data[len(data) // 2:]
f1, f2 = Counter(first), Counter(second)
code1, code2 = huffman_lengths(f1), huffman_lengths(f2)
missing = [bytes([b]) for b in f2 if b not in f1]
coded = [b for b in second if b in code1]
print(f"bytes in the second half with no codeword in the first half's code: {missing}")
print(f"second half with its own code:         {sum(f2[b] * code2[b] for b in f2) / len(second):.4f} bits per byte")
print(f"second half with the first half's code: {sum(code1[b] for b in coded) / len(coded):.4f} bits per byte (bytes that have a codeword)")
Text
bytes in the second half with no codeword in the first half's code: [b'3', b'$']
second half with its own code:         4.8135 bits per byte
second half with the first half's code: 4.8165 bits per byte (bytes that have a codeword)

The first half of the plays never uses "3" or "$", so a code built from it has no codeword for them, and coding the second half fails as soon as one appears (chapter 3's zero-frequency problem, in code form). For the bytes that do have codewords, the first half's code costs 4.8165 bits per byte on the second half against 4.8135 for the second half's own code: a small loss here, because the plays' statistics are stable, and a large one for data that changes. Real formats either build each block's code from that block (DEFLATE), reserve codewords for every possible symbol, or adapt.

2. "Huffman is within 1 bit of the entropy", which is the worst case, not the usual one. Robert Gallager (1978) proved a much sharper bound: when no symbol has probability above 12, Huffman's excess over the entropy is at most pmax+0.0861, where pmax is the largest probability.

Python
import math, random
from huff import huffman_lengths
SIGMA = 1 - math.log2(math.e) + math.log2(math.log2(math.e))    # about 0.0861
random.seed(8)
worst, worst_ratio, n = 0.0, 0.0, 0
while n < 5000:
    w = [random.random() ** 4 for _ in range(random.randint(3, 30))]
    p = {i: x / sum(w) for i, x in enumerate(w)}
    pmax = max(p.values())
    if pmax >= 0.5:
        continue                     # Gallager's simple bound is for p_max < 1/2
    n += 1
    H = sum(-q * math.log2(q) for q in p.values())
    L = sum(p[s] * l for s, l in huffman_lengths(p).items())
    worst = max(worst, L - H)
    worst_ratio = max(worst_ratio, (L - H) / (pmax + SIGMA))
print(f"5,000 random distributions with no symbol above 1/2:")
print(f"largest excess of Huffman over the entropy: {worst:.4f} bits (the general bound says under 1)")
print(f"largest excess as a share of p_max + {SIGMA:.4f}: {worst_ratio:.1%}")
Text
5,000 random distributions with no symbol above 1/2:
largest excess of Huffman over the entropy: 0.4107 bits (the general bound says under 1)
largest excess as a share of p_max + 0.0861: 83.7%

Over 5,000 random distributions, the worst excess was 0.41 bits, and never more than 84 % of Gallager's bound. The "1 bit" figure comes from sources dominated by one very likely symbol, where Huffman's one-digit floor bites (the exercises' T5). For spread-out distributions like text, Huffman is typically within a few hundredths of a bit (0.038 for the plays' bytes), and the real gap to good compression is the model (context), not the coder.

3. "Rare symbols get long codewords", and how long they can get. A Huffman code for K symbols can have codewords up to K−1 digits long. Counts that grow like Fibonacci numbers force it:

Python
from huff import huffman_lengths
fib = [1, 1]
while len(fib) < 25:
    fib.append(fib[-1] + fib[-2])
lengths = huffman_lengths({i: w for i, w in enumerate(fib)})
print("weights:", fib[:8], "...", fib[-1])
print("longest codeword:", max(lengths.values()), "digits, for", len(fib), "symbols; shortest:", min(lengths.values()))
print(f"rarest symbol's share of the total: 1 in {sum(fib):,}")
Text
weights: [1, 1, 2, 3, 5, 8, 13, 21] ... 75025
longest codeword: 24 digits, for 25 symbols; shortest: 1
rarest symbol's share of the total: 1 in 196,417

With 25 symbols weighted 1, 1, 2, 3, 5, 8, …, the tree is a single long chain: each merge combines the newest subtree with the next symbol, and the two rarest symbols get 24-digit codewords. It happens only when the rarest symbol's share is tiny (here 1 in 196,417), but a block of a few hundred thousand symbols can easily produce such counts. Table-driven decoders need a bound, so DEFLATE caps lengths at 15 and encoders must rebalance the tree when Huffman exceeds it, at a tiny cost in compression.

Common misconceptions

Misconception What's actually true Where it's shown
"A Huffman code built once works for similar data." Symbols it never saw have no codeword at all. What the chapter oversimplifies, point 1
"Huffman usually wastes up to a bit per symbol." For spread-out distributions the excess is at most pmax+0.086, usually far less. What the chapter oversimplifies, point 2
"Huffman codewords stay short." They can reach K−1 digits; formats cap them. What the chapter oversimplifies, point 3
"Huffman codewords are written high bit first in DEFLATE." zlib reverses them: DEFLATE packs bits from the least significant end. Code walkthrough
"Any priority queue implementation will do." Without a tie-breaker, Python's heap compares the trees and crashes. Drill D1
"Canonical codes are just counting upwards." Without shifting when the length grows, the code isn't prefix-free. Drill D2
"A one-symbol file needs no special case." Zero-length codewords carry nothing; the decoder can't count symbols. Drill D3
"Rice codes work for any whole number." Negative numbers collide with positive ones unless mapped first. Drill D4

Theoretical gaps: the ideas behind the chapter

  • Redundancy bounds. Beyond Gallager's pmax+0.086, sharper bounds depend on more of the distribution; they explain why Huffman is nearly perfect for text and poor for skewed binary sources.
  • Dyadic distributions. Distributions whose probabilities are all powers of 12 are exactly those a prefix code matches perfectly. Every distribution is within a factor of two of a dyadic one, which is another way to see the Shannon code's bound.
  • The Huffman tree as a sum of internal weights. The average codeword length equals the sum of the weights of the merged nodes (the Deeper page derives it), which is why a priority queue of weights is all the algorithm needs, and why Huffman runs in O(KlogK) time.

Applying it

Code walkthrough

zlib, the library inside gzip, PNG and countless programs, builds DEFLATE's canonical codes in a short function. Excerpt from trees.c in zlib 1.3.1 (github.com/madler/zlib, tag v1.3.1):

C
local void gen_codes(ct_data *tree, int max_code, ushf *bl_count) {
    ush next_code[MAX_BITS+1]; /* next code value for each bit length */
    unsigned code = 0;         /* running code value */
    int bits;                  /* bit index */
    int n;                     /* code index */

    /* The distribution counts are first used to generate the code values
     * without bit reversal.
     */
    for (bits = 1; bits <= MAX_BITS; bits++) {
        code = (code + bl_count[bits - 1]) << 1;
        next_code[bits] = (ush)code;
    }
    /* Check that the bit counts in bl_count are consistent. The last code
     * must be all ones.
     */
    Assert (code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
            "inconsistent bit counts");
    ...
    for (n = 0;  n <= max_code; n++) {
        int len = tree[n].Len;
        if (len == 0) continue;
        /* Now reverse the bits */
        tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
        ...
    }
}

bl_count[b] is the number of symbols whose codeword has b digits. The first loop computes, for each length, the first codeword of that length: take the first code of the previous length, skip past the codes of that length, and shift left one place, exactly the chapter's canonical rule. The Assert is Kraft's inequality with equality: if the code is complete, the last codeword of the longest length is all ones. The second loop hands out codewords in symbol order within each length, and bi_reverse reverses each one, because DEFLATE writes bits starting from the least significant end of each byte, so a codeword must be stored back to front to come out in the right order. Measured, with a Python transcription of the function:

Python
from collections import Counter
from huff import huffman_lengths, canonical_code
MAX_BITS = 15
def gen_codes(lengths):
    """A Python transcription of zlib's gen_codes (trees.c, v1.3.1), without the final bit reversal."""
    bl_count = [0] * (MAX_BITS + 1)
    for l in lengths:
        bl_count[l] += 1
    bl_count[0] = 0
    next_code, code = [0] * (MAX_BITS + 1), 0
    for bits in range(1, MAX_BITS + 1):
        code = (code + bl_count[bits - 1]) << 1
        next_code[bits] = code
    assert code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1, "inconsistent bit counts"
    out = []
    for l in lengths:
        out.append(format(next_code[l], f"0{l}b") if l else None)
        if l:
            next_code[l] += 1
    return out
# The example in RFC 1951, section 3.2.2: symbols A to H with these lengths
print("RFC 1951 example:", dict(zip("ABCDEFGH", gen_codes([3, 3, 3, 3, 3, 2, 4, 4]))))
f = Counter(open("data/shakespeare.txt", "rb").read())
lengths = huffman_lengths(f)
ours = canonical_code(lengths)
theirs = gen_codes([lengths.get(b, 0) for b in range(256)])
print("Shakespeare's 65 codewords identical to zlib's rule:", all(ours[b] == theirs[b] for b in f))
try:
    gen_codes([1, 1, 2])
except AssertionError as e:
    print("lengths 1, 1, 2:", e)
Text
RFC 1951 example: {'A': '010', 'B': '011', 'C': '100', 'D': '101', 'E': '110', 'F': '00', 'G': '1110', 'H': '1111'}
Shakespeare's 65 codewords identical to zlib's rule: True
lengths 1, 1, 2: inconsistent bit counts

For RFC 1951's own example (symbols A to H with lengths 3, 3, 3, 3, 3, 2, 4, 4), the transcription produces the codewords the RFC lists: F = 00, A = 010 to E = 110, G = 1110, H = 1111. For the plays' 65 bytes it produces exactly the codewords of the chapter's canonical_code. And for lengths 1, 1, 2, which fail Kraft's inequality, the consistency check fires.

Read it yourself

Using the code above: what does the Assert check for lengths 1, 2, 3 (a code that satisfies Kraft but isn't complete), and what does that tell you about the codes zlib expects? Why is reversing the bits necessary, and what goes wrong if a decoder forgets?

Debugging drills

D1. A Huffman builder that crashes on ties

A Huffman builder works on "aaaabbc" and crashes on "abracadabra".

Python
import heapq
from collections import Counter
def huffman_lengths(freqs):
    heap = [(w, {s: 0}) for s, w in freqs.items()]
    heapq.heapify(heap)
    while len(heap) > 1:
        w1, a = heapq.heappop(heap)
        w2, b = heapq.heappop(heap)
        heapq.heappush(heap, (w1 + w2, {s: d + 1 for s, d in (a | b).items()}))
    return heap[0][1]
print(huffman_lengths(Counter("aaaabbc")))
try:
    print(huffman_lengths(Counter("abracadabra")))
except TypeError as e:
    print("TypeError:", e)
Text
{'c': 2, 'b': 2, 'a': 1}
TypeError: '<' not supported between instances of 'dict' and 'dict'

D2. A canonical code that isn't prefix-free

A canonical code builder produces codewords 0, 01 and 10 for lengths 1, 2, 2, and the decoder loses symbols.

Python
def canonical(lengths):
    code, out = 0, {}
    for s, l in sorted(lengths.items(), key=lambda kv: (kv[1], kv[0])):
        out[s] = format(code, f"0{l}b")
        code += 1
    return out
code = canonical({"a": 1, "b": 2, "c": 2})
print(code)
inverse = {v: k for k, v in code.items()}
msg = "bca"
bits = "".join(code[c] for c in msg)
out, cur = "", ""
for b in bits:
    cur += b
    if cur in inverse:
        out += inverse[cur]; cur = ""
print(f"{msg} -> {bits} -> {out}")
Text
{'a': '0', 'b': '01', 'c': '10'}
bca -> 01100 -> a

D3. A file of one repeated byte vanishes

A compressor built on a textbook Huffman builder produces zero bits for a file of 1,000 zero bytes, and the decompressor returns an empty file.

Python
import heapq, itertools
from collections import Counter
def huffman_lengths(freqs):
    tie = itertools.count()
    heap = [(w, next(tie), {s: 0}) for s, w in freqs.items()]
    heapq.heapify(heap)
    while len(heap) > 1:
        w1, _, a = heapq.heappop(heap); w2, _, b = heapq.heappop(heap)
        heapq.heappush(heap, (w1 + w2, next(tie), {s: d + 1 for s, d in (a | b).items()}))
    return heap[0][2]
data = b"\x00" * 1000
lengths = huffman_lengths(Counter(data))
bits = "".join("0" * lengths[b] for b in data)
print("lengths:", lengths, "| coded bits:", len(bits), "| bytes the decoder can recover from them: 0 of", len(data))
Text
lengths: {0: 0} | coded bits: 0 | bytes the decoder can recover from them: 0 of 1000

D4. Rice codes that make 1 and −1 the same

An audio coder codes the differences between samples with a Rice code, and decoded audio has wrong signs.

Python
def rice(n, k):
    q, r = n >> k, n & ((1 << k) - 1)
    return "1" * q + "0" + format(r, f"0{k}b")
samples = [100, 102, 101, 99, 98, 100]                     # audio samples; code the change from the previous one
diffs = [b - a for a, b in zip(samples, samples[1:])]
print("differences:", diffs)
print("coded:", [rice(d, 1) for d in diffs])
print("rice(1, 1) =", rice(1, 1), "| rice(-1, 1) =", rice(-1, 1), "| rice(0, 1) =", rice(0, 1), "| rice(-2, 1) =", rice(-2, 1))
Text
differences: [2, -1, -2, -1, 2]
coded: ['100', '01', '00', '01', '100']
rice(1, 1) = 01 | rice(-1, 1) = 01 | rice(0, 1) = 00 | rice(-2, 1) = 00

Career-oriented

Interview prep

Mid level

Q1. Explain Huffman coding and why it's optimal.

How to get there. The algorithm, then the exchange-and-merge argument.

Q2. How does a decoder read a Huffman-coded stream, and how does it know the code?

How to get there. Prefix property, tree walk or tables, canonical codes.

Senior level

Q3. When is Huffman coding a poor choice, and what would you use instead?

How to get there. The one-bit floor, adaptivity, and modelling.

Q4. A protocol designer wants to save bandwidth by Huffman-coding a stream of small messages, each coded separately. What do you advise?

How to get there. Per-message overhead, static codes, shared tables.

Staff level

Q5. Your team maintains a storage format that Huffman-codes columns with a table per file. Files are getting smaller (many small files from streaming ingestion), and compression ratios are falling. Diagnose and propose a strategy.

How to get there. Table overhead per file, and statistics shared across files.

Q6. A candidate claims a new prefix code beats Huffman by 3 % on your test files. How do you evaluate it?

How to get there. Optimality of Huffman, and what the comparison really measured.