Sub topic 13
Adaptive Huffman Coding
This chapter assumes you can already build a static Huffman tree with a min-heap, encode and decode with a prefix-free code, and follow why compressed files ship a code table (covered in earlier chapters). It also assumes you are comfortable reading recursive Python.
Static Huffman coding makes two passes over the data. The first pass counts symbols, and the second encodes them. The code table, or the code lengths of a canonical code, goes in front of the data. Adaptive Huffman coding removes the first pass. The encoder and decoder both begin with the same model and update it after every symbol, so the code changes as the message goes by and no table is sent.
Why Adapt at All
The two-pass approach has three practical costs:
- You need all the data up front. A live stream, a pipe, or a network socket can't be counted before it is encoded.
- The table costs bits. For short messages or large alphabets, the header can eat most of the savings.
- One table covers the whole file. If the first half is mostly English text and the second half is mostly digits, a single set of frequencies fits neither half well.
An adaptive coder handles all three. The trade-off is more computation per symbol, a slow start while the model learns, and a decoder that must copy the encoder's state changes exactly.
The Core Idea: Encoder and Decoder in Lockstep
The rule that makes adaptive coding work is simple: encode each symbol with the model built from the symbols before it, then update. The decoder has already decoded those same earlier symbols, so it can build the same model before it reads the next code.
A Naive Adaptive Coder
The simplest correct version rebuilds the whole Huffman tree before every symbol. It is slow, but it shows the protocol clearly. Every symbol of a known alphabet starts with count 1, so every symbol has a code from the first step.
import heapq
from itertools import count
def codes_from_counts(counts):
# Sorting the items makes tie-breaking deterministic,
# so encoder and decoder always build the same tree.
tiebreak = count()
heap = [(f, next(tiebreak), sym) for sym, f in sorted(counts.items())]
heapq.heapify(heap)
if len(heap) == 1:
return {heap[0][2]: "0"}
while len(heap) > 1:
f1, _, a = heapq.heappop(heap)
f2, _, b = heapq.heappop(heap)
heapq.heappush(heap, (f1 + f2, next(tiebreak), (a, b)))
codes = {}
def walk(node, prefix):
if isinstance(node, tuple):
walk(node[0], prefix + "0")
walk(node[1], prefix + "1")
else:
codes[node] = prefix
walk(heap[0][2], "")
return codes
def encode_adaptive(text, alphabet):
counts = {s: 1 for s in alphabet}
out = []
for ch in text:
codes = codes_from_counts(counts)
out.append(codes[ch])
counts[ch] += 1
return "".join(out)
def decode_adaptive(bits, alphabet, n_symbols):
counts = {s: 1 for s in alphabet}
out, pos = [], 0
for _ in range(n_symbols):
reverse = {c: s for s, c in codes_from_counts(counts).items()}
current = ""
while current not in reverse:
current += bits[pos]
pos += 1
sym = reverse[current]
out.append(sym)
counts[sym] += 1
return "".join(out)
alphabet = "abcdr"
text = "abracadabra"
bits = encode_adaptive(text, alphabet)
assert decode_adaptive(bits, alphabet, len(text)) == text
print(len(bits), "bits, no table needed")The decoder needs to know when to stop. This version passes n_symbols separately. Real formats either store the length in the header or reserve an end-of-stream symbol in the alphabet.
Rebuilding costs O(k log k) per symbol for an alphabet of k symbols. For bytes (k = 256) that cost is too high. The classic algorithms update the existing tree in place.
FGK: Updating the Tree Incrementally
The FGK algorithm, named for Faller (1973), Gallager (1978), and Knuth (1985), relies on a property Gallager proved.
Sibling property: a binary code tree with weighted nodes is a Huffman tree if and only if its nodes can be numbered in order of non-increasing weight so that nodes 2j−1 and 2j are siblings for every j. (Every node except the root has a sibling.)
FGK keeps that numbering in an explicit list. Adding 1 to a leaf's weight, and to the weight of each of its ancestors, can break the ordering. The fix is to swap nodes before incrementing:
- Start at the leaf for the symbol just coded.
- Find the highest-numbered node with the same weight as the current node. Its parent is excluded.
- If that node is not the current node, swap the two subtrees in the tree and swap their positions in the numbering.
- Increment the current node's weight.
- Move to the parent and repeat until you have incremented the root.
Each step does constant work if you keep a lookup from weight to the highest-numbered node of that weight. The whole update therefore costs time proportional to the symbol's code length, which is the same order as emitting the code.
The NYT Node: Handling Unseen Symbols
The naive coder gave every symbol a starting count of 1, which wastes code space on symbols that never appear. FGK instead starts with a single leaf called NYT ("not yet transmitted") with weight 0. When a symbol appears for the first time:
- The encoder emits the current code for NYT, followed by the symbol in a fixed raw form, such as 8 bits for a byte.
- The NYT leaf splits into two children: a new NYT leaf with weight 0 and a leaf for the new symbol.
- The normal update runs from the new symbol's leaf.
When the decoder reaches the NYT leaf, it reads the raw bits that follow, adds the symbol, and makes the same split.
Vitter's Algorithm
Vitter's Algorithm V (1987) changes how nodes are ordered. Within each block of equal weight, leaves come before internal nodes. This keeps the tree shallower and minimizes both the sum of code lengths and the maximum code length among all Huffman trees for the current weights. Vitter showed that his method stays within about one bit per symbol of a two-pass static Huffman code, plus the cost of first occurrences. FGK's worst-case bound is roughly twice the static cost. In practice both are close on typical data, but Vitter's version adapts better on short inputs.
Comparing the Options
| Approach | Passes | Header cost | Per-symbol work | Notes |
|---|---|---|---|---|
| Static Huffman | 2 | Code lengths | O(1) table lookup | Fastest decode; one model for the whole block |
| Naive adaptive (rebuild) | 1 | None | O(k log k) | Easy to get right; too slow for real use |
| FGK | 1 | None | O(code length) | Sibling-property swaps; NYT escape |
| Vitter (Algorithm V) | 1 | None | O(code length) | Tighter bound, shallower trees |
| Adaptive arithmetic coding | 1 | None | O(1) to O(log k) | Fractional bits per symbol; works with context models |
Gotchas and Failure Modes
- Errors spread. One flipped bit changes the decoded symbol, which changes the model, and every symbol after it is wrong. Static Huffman can sometimes resynchronize. Adaptive coders almost never do, so put checksums or resync points around them.
- No random access. To decode symbol 1,000,000, you must replay all the updates before it.
- Slow start. Early symbols are coded with a model that has barely learned anything. On short messages, this can cost more than a compact canonical header would.
- Counter overflow and staleness. Counts grow without limit. A common fix is to halve every count when the root weight reaches a threshold. This also gives recent symbols more weight than old ones, which helps when the source changes over time. Both sides must rescale at exactly the same point.
- Whole-bit codes remain. Adaptation does not fix Huffman's main limitation: a symbol with probability 0.95 still costs at least 1 bit. This is why modern adaptive coders use arithmetic coding or ANS with adaptive probability models instead of adaptive Huffman trees.
Exercise
In the naive adaptive coder, suppose the encoder used counts.items() without sorting while the decoder sorted them. Why could decoding fail even though both sides hold identical counts?
Show answer
When two subtrees have equal counts, the heap orders them by the tiebreak counter, which comes from insertion order. Different insertion orders can therefore produce different trees with the same counts, so the codes differ and the decoder reads the wrong symbols. Both sides need the same deterministic order.
Exercise
An FGK encoder sees the symbol 'x' for the first time. List what it emits and how the tree changes.
Show answer
It emits the current code for the NYT leaf, then the raw fixed-width encoding of 'x'. The NYT leaf becomes an internal node with two children: a new weight-0 NYT leaf and a leaf for 'x'. The update then runs from the 'x' leaf up to the root, swapping nodes where needed to keep the sibling property and incrementing weights.
Exercise
Give two reasons a format designer might choose block-wise static Huffman with canonical tables over Vitter's adaptive Huffman.
Show answer
Static tables decode faster, because a lookup table replaces per-symbol tree updates. They also limit the damage from bit errors and allow decoding to start at a block boundary. Re-sending a compact table each block still lets the code follow changes in the data.