Workbench / Information Theory Exercises
B1·05
Codes: Prefix Codes, Kraft's Inequality and Huffman Coding
Exercises for chapter 5: unique decodability, prefix codes as trees, Kraft's inequality, the entropy bound, why Huffman works and where it doesn't, and integer codes; a full Huffman encoder and decoder with canonical codes, a Kraft checker tested on 20,000 length lists, Huffman against Shannon–Fano on 5,000 distributions, Huffman on blocks of sensor reports, a word-level Huffman code with its dictionary paid for, and senior exercises on random access, one table per block, and what a flipped bit does.
Start here: how these exercises work
Write your answer in the box first; hints open one at a time as you write, and the solution a couple of minutes after the last hint. Theory is in your own words, practice and programs come with real output (Python 3.13), cumulative projects use chapters 1 to 5 together, what the chapter leaves out explains what it skips, and senior exercises put the ideas into designs and reviews. The programs import the chapter's huff.py.
Theory
T1. Why separators aren't needed
Explain to someone who has never seen a prefix code how 0110100 can be read as A C B A with A = 0, B = 10, C = 110, D = 111, without any gaps, and why the same trick fails with A = 0, B = 01, C = 10.
T2. Kraft's inequality as a budget
Explain Kraft's inequality as a budget: what is being shared out, how much does a codeword of length cost, and why can't the total exceed 1?
T3. Why no code beats the entropy
In your own words, explain why the average length of a code can't be less than the entropy, using the budget picture of T2 and chapter 1's surprise.
T4. Bottom-up, not top-down
Shannon–Fano coding splits symbols top-down into two groups of nearly equal probability; Huffman merges bottom-up. Explain why bottom-up merging is guaranteed optimal and top-down splitting isn't.
T5. The one-bit floor
Explain why a Huffman code can't spend less than one binary digit per symbol, and give a source where that matters enormously. What can be done instead?
T6. Gamma or Rice?
When would you choose Elias gamma, and when a Rice code, for coding whole numbers? What does each assume about the numbers?
Practice and programs
P1. By hand
(a) Is {00, 01, 100, 101, 11} a prefix code? Complete? (b) Build a Huffman code for counts A 7, B 5, C 2, D 1, E 1 and give the coded length of the 16 symbols. (c) Which lengths does a Huffman code give four equally likely symbols? Five? (d) Give the Rice code of 20 with .
P2. A Huffman encoder and decoder
Write encode(text) that builds a canonical Huffman code from the text's character counts and returns the code and the bit string, and decode(bits, code) that reads it back, raising an error if bits are left over. Test the round trip on 20,000 characters of the plays, and try decoding with one bit missing.
P3. Kraft's inequality, tested
Write kraft(lengths) with exact fractions and build(lengths) that returns canonical codewords for the lengths (in the given order) or None if Kraft fails. Test on 20,000 random lists of lengths: every list that passes must produce a prefix-free code with exactly those lengths.
P4. Huffman against Shannon–Fano
Implement Shannon–Fano coding (sort, split at the point where the two halves' totals are closest, recurse) and compare it with Huffman on 5,000 random distributions of 2 to 20 symbols. Check that Huffman is always between and , and count how often each wins.
Cumulative projects (chapters so far: 01–05)
C1. Huffman for the sensor, one report and several
Chapter 4's sensor reports one of 8 states with probabilities 0.65, 0.2, 0.1, 0.02, 0.01, 0.01, 0.005, 0.005. Build Huffman codes for single reports and for blocks of 2 and 3 reports, and compare their cost per report with the entropy and with the strategies of chapter 4's C1. What's the price of the blocks?
C2. A word-level Huffman code, paying for its dictionary
Split the plays into words and single non-letter characters, build a Huffman code for these tokens, and compute the coded size plus the cost of sending the dictionary (each token spelled out, and its codeword length). Compare with byte-level Huffman (671,611 bytes) and lzma (364,052).
What the chapter leaves out
Arithmetic coding
Huffman gives each symbol a whole number of digits. Arithmetic coding (Rissanen, Pasco, 1976) gives up codewords altogether: it codes a whole message as a single number in an interval that shrinks by each symbol's probability, so a symbol of probability effectively costs , fractions included. It removes Huffman's one-bit floor and its up-to-one-bit rounding, and it pairs naturally with adaptive and context models. Chapter 6 builds one.
Lempel–Ziv and dictionary methods
Huffman needs probabilities. Abraham Lempel and Jacob Ziv's methods (LZ77 and LZ78) need none: they replace a repeated string with a pointer to an earlier copy. They are universal: for long inputs from any stationary source, they approach its entropy rate without being told the statistics. DEFLATE combines LZ77 with Huffman coding of the pointers and literals, which is why zip files contain both ideas. Chapter 6 explains why universality is possible.
Length-limited and fast Huffman decoding
Real decoders don't walk a tree bit by bit; they read several bits at once and look the result up in a table. Long codewords make the tables big, so formats limit codeword length (DEFLATE to 15, JPEG to 16) and use the package-merge algorithm (Larmore and Hirschberg, 1990) to find the best code within the limit. Modern libraries (zlib-ng, libdeflate, Zstandard's Huffman stage) decode several streams in parallel to keep the processor busy.
Tunstall codes
Huffman maps fixed-size inputs (one symbol) to variable-length outputs. Brian Tunstall's code (1967) does the opposite: variable-length input strings to fixed-length output codewords, which is useful when the decoder needs to know exactly where each codeword starts, or when the output must be fixed-size blocks.
Senior exercises
S1. Random access or compression?
A mobile game ships a 50 MB table of tile types (one of 40 types per tile) and reads individual tiles at random positions thousands of times a second. A colleague proposes Huffman-coding the table to halve its size. Evaluate, and propose a design that gets most of the saving without losing random access.
S2. One Huffman table, or one per block?
DEFLATE starts a new Huffman table for each block of data. Code the plays with a separate byte-level Huffman table for each block, at block sizes from 1,000 bytes to the whole file, counting 4 bits per byte value for each table. What's the best block size here, and when would smaller blocks win?
S3. What does one flipped bit do?
Huffman-code 5,000 characters of the plays, flip a single bit at four positions, decode, and measure how many characters are garbled before the decoder gets back in step. Then explain why compressed data still needs protection, even though the damage here is small.