Sub topic 12
Limitations: Whole-Bit Lengths, Skewed Sources, and Edge Cases
This chapter assumes you have built Huffman trees with a min-heap, encoded and decoded bitstreams, and compared average code length with Shannon entropy in the earlier chapters. You should also be comfortable reading Python that uses heapq and itertools.
Huffman coding is optimal, but only within a narrow definition of the problem. It gives the best possible prefix code that assigns a whole number of bits to each symbol independently, using fixed, known probabilities. Real data and real files break those assumptions often. This chapter goes through where the method falls short, how to spot each problem, and what to use instead.
The Whole-Bit Constraint
Each Huffman codeword has an integer length. The ideal length for a symbol with probability p is −log₂ p bits, and that value is rarely a whole number. Huffman rounds each ideal length up or down so the lengths still fit in a valid tree. The rounding costs up to one bit per symbol on average. That gives the bound from the entropy chapter:
H ≤ L < H + 1
where H is the entropy and L is the average code length.
When the entropy is large, say 4 or 5 bits per symbol for English text, losing a fraction of a bit is a small relative cost. When the entropy is small, the same fraction can be most of the output.
Skewed Sources
Take a binary source where a has probability 0.9 and b has probability 0.1. The entropy is about 0.469 bits per symbol. Huffman can only give each symbol a 1-bit code, because a code needs at least one bit and there are only two symbols. The output is therefore more than twice the ideal size.
The extreme case is a source where one symbol has probability 0.999. The entropy is about 0.011 bits per symbol, and Huffman still spends 1 bit. The output is roughly 90 times larger than the entropy bound.
Workaround: Block Coding
One fix is to code groups of k symbols as single "super-symbols." The alphabet grows to (alphabet size)^k, and the one-bit rounding loss is spread over k symbols. The loss per original symbol is then below 1/k bits.
import heapq
import math
from itertools import count, product
def huffman_lengths(probs):
tiebreak = count()
heap = [(p, next(tiebreak), [sym]) for sym, p in probs.items()]
heapq.heapify(heap)
if len(heap) == 1:
return {sym: 1 for sym in probs}
lengths = {sym: 0 for sym in probs}
while len(heap) > 1:
p1, _, s1 = heapq.heappop(heap)
p2, _, s2 = heapq.heappop(heap)
for sym in s1 + s2:
lengths[sym] += 1
heapq.heappush(heap, (p1 + p2, next(tiebreak), s1 + s2))
return lengths
def block_probs(probs, k):
out = {}
for combo in product(probs, repeat=k):
p = 1.0
for sym in combo:
p *= probs[sym]
out["".join(combo)] = p
return out
source = {"a": 0.9, "b": 0.1}
H = -sum(p * math.log2(p) for p in source.values())
for k in (1, 2, 3):
bp = block_probs(source, k)
lengths = huffman_lengths(bp)
avg = sum(bp[s] * lengths[s] for s in bp) / k
print(k, round(avg, 3), round(H, 3))The output is:
1 1.0 0.469
2 0.645 0.469
3 0.533 0.469Block coding works, but it has a cost. The alphabet grows exponentially. A byte alphabet blocked in pairs has 65,536 symbols, and in triples it has more than 16 million. The code table grows at the same rate, and so do the counts you need before the probability estimates are reliable. In practice, block coding helps small alphabets and fails for large ones.
The Real Fix: Arithmetic and ANS Coding
Arithmetic coding and asymmetric numeral systems (ANS) skip codewords entirely. They encode the whole message as one number, or as a state that evolves, so each symbol can effectively cost a fractional number of bits. Their output comes within a tiny overhead of the entropy, even on skewed sources. Modern formats such as Zstandard (which uses the tANS variant called FSE), the CABAC coder in H.264 and HEVC, and JPEG's optional arithmetic mode use these methods for exactly this reason. The cost is more arithmetic per symbol and, historically, patent concerns. That is a large part of why baseline JPEG and DEFLATE kept Huffman.
Model Limitations
Huffman is only an entropy coder. It turns probabilities into bits, and it is only as good as the probabilities you give it.
No Context
A plain Huffman code is an order-0 model, which means each symbol is coded as though it were independent of its neighbours. In English, u after q is almost certain, but an order-0 code charges for u at its overall frequency. The repetition in abcabcabcabc is invisible to it: it sees three equally frequent symbols and spends about 1.58 bits on each. Real compressors put a modelling stage first, such as LZ77 matching in DEFLATE or the DCT plus run-length step in JPEG. That stage turns structure into skewed symbol statistics, and Huffman then codes those.
Static Statistics
A static Huffman code needs the frequencies before it can encode anything. That causes two problems:
- Two passes. The encoder must read the data once to count and again to encode. Streaming input with no lookahead cannot do this.
- Non-stationary data. A file whose statistics change partway through, such as text followed by a binary blob, gets one compromise code that fits neither part well.
DEFLATE handles non-stationary data by splitting the stream into blocks, each with its own code. Adaptive Huffman coding, covered in the next chapter, updates the tree as symbols arrive.
Table Overhead
The decoder needs the code. Even with canonical codes that send only lengths, a block pays a fixed header cost. For a short message, the header can be larger than the savings. This is why DEFLATE also offers a "fixed Huffman" block type with a predefined code and no header, and a "stored" block type for data that does not compress.
Edge Cases That Break Naive Implementations
| Case | What goes wrong | Handling |
|---|---|---|
| Empty input | The heap is empty, so `heap[0]` raises `IndexError` | Return an empty code and emit an empty stream |
| One distinct symbol | The tree is a single leaf with depth 0, so the code would be the empty string | Assign a 1-bit code, or store only the symbol and a count |
| Ties in frequency | Different tie orders give different trees | Use a deterministic tie-breaker; canonical codes remove the ambiguity |
| Very uneven frequencies | Code lengths grow to n − 1 bits | Limit code lengths (see the length-limited chapter) |
| Final byte padding | Leftover pad bits can decode as extra symbols | Store the symbol count, or code an end-of-block symbol |
| Bit errors | One flipped bit shifts codeword boundaries | Add framing, checksums, or resync markers |
Pathologically Long Codes
When frequencies follow the Fibonacci sequence, each merge combines the newest subtree with the next leaf. The tree becomes a chain, and the deepest code is n − 1 bits long. Run this after the earlier script, because it reuses huffman_lengths:
fib = [1, 1]
while len(fib) < 20:
fib.append(fib[-1] + fib[-2])
weights = {"s{}".format(i): w for i, w in enumerate(fib)}
lengths = huffman_lengths(weights)
print(max(lengths.values())) # 19Twenty symbols are enough to produce a 19-bit code. With a few thousand symbols, codes can be longer than a machine word, which breaks table-driven decoders. This is why DEFLATE caps code lengths at 15 bits and baseline JPEG caps them at 16.
Padding and Termination
A bitstream is usually written out in whole bytes, so the last byte gets padded. If the pad bits happen to form a valid codeword, a naive decoder outputs extra symbols. Either store the original length, or add an end-of-block symbol to the alphabet, as DEFLATE does with symbol 256.
Error Propagation
Variable-length codes have no fixed boundaries. A single corrupted bit can make the decoder lose track of where codewords start. Huffman codes often resynchronize after a few symbols, but nothing guarantees it, and every symbol in between is wrong. Formats that need resilience add markers. JPEG's restart markers are one example.
Choosing a Coder
The 0.5 threshold is a rule of thumb. Once one symbol is that likely, its ideal length drops below 1 bit, and Huffman's whole-bit rounding starts to dominate the loss.
Exercise
A source emits symbol x with probability 0.99 and symbol y with probability 0.01. What is the Huffman average code length per symbol, what is the entropy (to two decimals), and roughly how many times larger is the Huffman output than the entropy bound?
Show answer
Huffman must give each symbol 1 bit, so the average is 1 bit per symbol. The entropy is −(0.99·log₂0.99 + 0.01·log₂0.01) ≈ 0.0144 + 0.0664 ≈ 0.08 bits. The Huffman output is about 12 times larger than the entropy bound.
Exercise
The build_codes function from the tree-building chapter is called with an empty string. What happens, and what is the simplest fix?
Show answer
The heap is empty, so the len(heap) == 1 check fails, the while loop is skipped, and heap[0][2] raises IndexError. The simplest fix is to return {} right after the frequency count when the text is empty, and have the encoder produce an empty bitstream.
Exercise
Why does Huffman coding alone compress "abcabcabcabc" poorly, and what kind of stage would fix it?
Show answer
Huffman is order-0. It sees three equally frequent symbols and spends about 1.58 bits on each, because it cannot see the repetition. A modelling stage such as LZ77, which replaces repeats with (distance, length) references, turns that repetition into a few skewed symbols that Huffman can then code compactly.