Sub topic 13
Adaptive Huffman Coding
This chapter assumes you already know how the static Huffman algorithm builds a tree with a min-heap, how prefix-free decoding works, and the limitations covered in the previous chapter. Static Huffman needs two passes over the data. The first pass counts symbols and the second encodes them, and the code table has to travel with the compressed output. Adaptive Huffman coding removes both requirements. It builds the code while it reads the data.
The working model: encoder and decoder keep the same counts
In the adaptive scheme, the encoder and the decoder start from the same initial model and update it in the same way after every symbol. The encoder codes each symbol with the current tree and then increments that symbol's count. The decoder reads bits with its current tree until it reaches a leaf, outputs that symbol, and then makes the same increment. Because both sides always hold identical counts, they always hold identical trees, so no table is ever sent.
A naive version you can run
The simplest correct version rebuilds the whole Huffman code after every symbol. It starts every symbol in a known alphabet at a count of 1, so no symbol ever has a count of zero.
import heapq
from itertools import count
def codes_from_counts(counts):
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 adaptive_encode(text, alphabet):
counts = {s: 1 for s in alphabet}
bits = []
for ch in text:
bits.append(codes_from_counts(counts)[ch])
counts[ch] += 1
return "".join(bits)
def adaptive_decode(bits, alphabet, n):
counts = {s: 1 for s in alphabet}
out, pos = [], 0
for _ in range(n):
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)
text = "abracadabra"
bits = adaptive_encode(text, "abcdr")
assert adaptive_decode(bits, "abcdr", len(text)) == text
print(bits, len(bits), "bits")The decoder needs the message length n because it has no other way to know where the stream ends. Real formats store the length or add an end-of-stream symbol.
Efficient updates: FGK and Vitter
Rebuilding the tree costs O(k log k) per symbol for an alphabet of k symbols. The FGK algorithm (Faller, Gallager, Knuth) and Vitter's algorithm instead update the existing tree in time proportional to the code length. Both rely on the sibling property: a tree is a Huffman tree exactly when its nodes can be listed in nondecreasing weight order with siblings next to each other. To increment a leaf, the algorithm swaps the node with the highest-ordered node of equal weight (never its own parent), increments it, and repeats at its parent up to the root.
These algorithms also handle unseen symbols without a preset alphabet. They use a zero-weight NYT (not yet transmitted) leaf. The first time a symbol appears, the encoder sends the NYT code followed by the symbol's raw bits. The NYT leaf then splits into a new NYT leaf and a leaf for the new symbol.
Common errors and trade-offs
| Issue | Effect |
|---|---|
| Encoder and decoder use different tie-breaking | The trees diverge and the output is garbage |
| Counts grow without limit | Old statistics dominate. Periodically halving counts lets the code track change |
| One flipped bit | Desynchronizes every later symbol, not just one |
Adaptive Huffman suits streaming data and sources whose statistics drift. It is slower per symbol than static Huffman. In practice, block-based static Huffman (as in DEFLATE) or adaptive arithmetic coding usually wins.
Exercise
In the naive code above, why is it safe for the decoder to call codesfromcounts before reading each symbol, even though it has not seen that symbol yet?
Show answer
The decoder's counts at that moment come only from symbols it has already decoded, and the encoder used exactly those counts to code the current symbol. Both sides therefore build the same tree, and the decoder updates its counts only after it has identified the symbol.
Exercise
In the FGK scheme, a stream starts with "xyx". What does the encoder send for each of the three symbols?
Show answer
For the first x, the tree holds only the NYT leaf, so its code is empty and the encoder sends just the raw bits for x. For y, it sends the current NYT code followed by the raw bits for y. For the second x, x is already in the tree, so it sends only x's current code.