Sub topic 12
Limitations: Whole-Bit Lengths, Skewed Sources, and Edge Cases
This chapter assumes you can already build a Huffman tree with a min-heap and compute Shannon entropy, as covered in earlier chapters. Huffman coding is optimal among codes that give each symbol its own whole number of bits. Most of its weaknesses come from that restriction, and the rest come from the assumptions it makes about the input.
The Whole-Bit Problem
Each codeword has an integer length, so no symbol can cost less than 1 bit. Entropy, in contrast, charges a symbol −log₂(p) bits, which is usually a fraction. When p is close to 1, the gap is large.
Suppose a source emits a with probability 0.99 and b with probability 0.01. The entropy is about 0.081 bits per symbol. Huffman can only give each symbol 1 bit, so it spends about 12 times what the entropy allows.
The guarantee H ≤ L < H + 1 is still true here, but the "+1" is the whole cost. The redundancy is small only when no single symbol dominates.
Blocking Symbols Together
One fix is to code pairs, or longer blocks, as single symbols. The 1-bit minimum then applies to the whole block instead of each symbol.
import heapq
import math
from itertools import count
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 s in s1 + s2:
lengths[s] += 1
heapq.heappush(heap, (p1 + p2, next(tiebreak), s1 + s2))
return lengths
def report(probs):
lengths = huffman_lengths(probs)
avg = sum(probs[s] * lengths[s] for s in probs)
h = -sum(p * math.log2(p) for p in probs.values() if p > 0)
print(f"H={h:.3f} avg={avg:.3f}")
single = {"a": 0.99, "b": 0.01}
pairs = {x + y: single[x] * single[y] for x in single for y in single}
report(single) # H=0.081 avg=1.000
report(pairs) # H=0.162 avg=1.030 (per pair)Coding pairs drops the cost from 1.0 to about 0.515 bits per original symbol. The price is an alphabet that grows exponentially with block size: blocks of k symbols over an alphabet of size n produce nᵏ entries. Arithmetic coding and asymmetric numeral systems (ANS) avoid this by spending fractional bits per symbol directly.
Model Assumptions
Huffman codes each symbol independently using one fixed frequency table. That causes two problems:
- It ignores context. In English,
uafterqis almost certain, but a plain Huffman coder still charges the average cost ofu. Formats like DEFLATE add a modeling stage such as LZ77 first. - It assumes stationary statistics. If the first half of a file is text and the second half is binary, one table fits neither half well. Per-block tables or adaptive Huffman coding help.
The code table is also overhead. For short inputs, storing it can cost more than the compression saves.
Edge Cases
| Case | What goes wrong | Usual handling |
|---|---|---|
| Empty input | Heap is empty, no tree exists | Return an empty table and emit no bits |
| One distinct symbol | Root is a leaf, so its code is `""` | Assign `"0"`, or store only the symbol and a count |
| Ties in frequency | Different trees and codes are possible | Average length is identical; use canonical codes so encoder and decoder agree |
| Fibonacci-like frequencies | Code lengths grow to n − 1 bits | Use length-limited Huffman |
Exercise
A source emits a with probability 0.9 and b with probability 0.1. What is Huffman's average length per symbol, and what does it become per original symbol if you code pairs?
Show answer
Single symbols get 1 bit each, so the average is 1.0 bit (entropy is about 0.469). The pairs have probabilities aa=0.81, ab=0.09, ba=0.09, bb=0.01, and Huffman gives them lengths 1, 3, 2, 3 (or 1, 2, 3, 3, depending on how the tie is broken). The average is 0.81 + 0.18 + 0.30 = 1.29 bits per pair, which is 0.645 bits per original symbol.
Exercise
Why does the textbook Huffman loop give a useless code for the input "aaaa", and what is a correct fix?
Show answer
The heap starts with one node, so the merge loop never runs and the only leaf is the root, with code "". Encoding produces zero bits. A fix is to assign the code "0" (4 bits total), or to store only the symbol and the message length.