Sub topic 14
Length-Limited Huffman Codes
This chapter assumes you can build Huffman code lengths with a min-heap, know the Kraft inequality in its basic form, and can turn a set of code lengths into canonical codes. Those topics were covered in earlier chapters. Here we deal with a practical problem: a plain Huffman tree can produce codes too long for a real format to store or decode efficiently.
Why Huffman Lengths Can Grow Too Long
Huffman's algorithm minimizes the average code length and places no limit on the longest code. With skewed frequencies the tree turns into a long chain. Fibonacci-like frequencies are the worst case: each new merged node is only just smaller than the next leaf, so every merge adds one level.
With frequencies 1, 1, 2, 3, 5, 8, 13, 21 for eight symbols, Huffman gives the rarest two symbols 7-bit codes. That is harmless for eight symbols. A 286-symbol DEFLATE alphabet with very uneven counts can, in principle, need codes of 20 bits or more, and formats can't accept that.
Why formats impose a maximum
| Format | Code type | Maximum length | Reason |
|---|---|---|---|
| DEFLATE | Literal/length and distance codes | 15 bits | Code lengths are stored as values 0–15 |
| DEFLATE | Code-length code | 7 bits | Its lengths are stored in 3-bit fields |
| JPEG | DC and AC tables | 16 bits | The header has a count for each length 1–16 |
Limits also help decoders. A table-driven decoder reads L bits at once and looks them up in a table with 2^L entries. A 15-bit limit means a 32,768-entry table at most, and a fixed bit buffer always holds a whole code. Without a limit, neither guarantee holds.
The Constraint in Terms of Kraft
A set of lengths l₁ … lₙ can be realized as a prefix-free code exactly when the Kraft sum Σ 2^(−lᵢ) ≤ 1. A length limit L adds lᵢ ≤ L for every symbol. Two consequences follow:
- With n symbols you need 2^L ≥ n. Eight-bit codes can't cover 300 symbols, because only 256 distinct 8-bit patterns exist.
- Shortening a long code raises the Kraft sum, so some other code has to get longer to pay for it. Length-limiting moves bits between symbols. It never removes them.
So the problem is: choose integer lengths in [1, L] with Kraft sum ≤ 1 that minimize Σ fᵢ·lᵢ. Plain Huffman solves the version without the upper bound. Two families of methods solve the bounded version.
Package-Merge: The Optimal Method
The package-merge algorithm (Larmore and Hirschberg, 1990) finds optimal length-limited lengths in O(nL) time. The idea is to treat each symbol as a set of "coins", one coin for each level the symbol might occupy. Paying for a code length of k means spending k of that symbol's coins. Picking the cheapest 2n − 2 coins across all levels gives the optimal lengths.
The working procedure:
- Sort the leaves (symbol, weight) by weight.
- Repeat L − 1 times: pair adjacent items of the current list into packages (summing weights and joining their symbol lists). Drop an unpaired last item. Merge the packages with a fresh copy of the leaves and sort by weight.
- Take the first 2n − 2 items of the final list. A symbol's code length is the number of those items that contain it.
import heapq
from collections import Counter
from itertools import count
def huffman_lengths(freqs):
if len(freqs) == 1:
return {next(iter(freqs)): 1}
tiebreak = count()
heap = [(f, next(tiebreak), [s]) for s, f in freqs.items()]
heapq.heapify(heap)
depth = Counter()
while len(heap) > 1:
f1, _, a = heapq.heappop(heap)
f2, _, b = heapq.heappop(heap)
for s in a + b:
depth[s] += 1
heapq.heappush(heap, (f1 + f2, next(tiebreak), a + b))
return dict(depth)
def package_merge(freqs, max_len):
n = len(freqs)
if n == 1:
return {next(iter(freqs)): 1}
if (1 << max_len) < n:
raise ValueError("2**max_len must be at least the number of symbols")
leaves = sorted(((f, [s]) for s, f in freqs.items()), key=lambda x: x[0])
current = list(leaves)
for _ in range(max_len - 1):
packages = [
(current[i][0] + current[i + 1][0], current[i][1] + current[i + 1][1])
for i in range(0, len(current) - 1, 2)
]
current = sorted(leaves + packages, key=lambda x: x[0])
lengths = Counter()
for _, syms in current[: 2 * n - 2]:
for s in syms:
lengths[s] += 1
return dict(lengths)
def kraft_sum(lengths):
return sum(2.0 ** -l for l in lengths.values())
def cost(freqs, lengths):
return sum(freqs[s] * lengths[s] for s in freqs)
freqs = dict(zip("abcdefgh", [1, 1, 2, 3, 5, 8, 13, 21]))
plain = huffman_lengths(freqs)
print("Huffman:", plain, "max", max(plain.values()), "cost", cost(freqs, plain))
limited = package_merge(freqs, 4)
print("Limit 4:", limited, "max", max(limited.values()), "cost", cost(freqs, limited))
print("Kraft sums:", kraft_sum(plain), kraft_sum(limited))Unlimited Huffman gives a maximum length of 7 and a total cost of 132 bits for this 54-symbol message. With a 4-bit limit, package-merge gives h and g 2 bits, f and e 3 bits, and the rest 4 bits, for a total of 135 bits. The limit costs 3 bits, about 2%. That is typical. Optimal length-limited codes are usually very close to unlimited Huffman, because only the rare symbols are affected and they contribute little to the total.
Checking the algorithm on a small case
For weights a:1, b:1, c:2, d:4 with L = 3, Huffman already fits (lengths 3, 3, 2, 1) and package-merge returns the same lengths. With L = 2, all four symbols get 2 bits. That is the only choice when 2² = 4 symbols must fit in 2 bits, since the Kraft sum is exactly 1.
Heuristic Repair: What zlib and JPEG Do
Many encoders skip package-merge and fix the Huffman lengths after the fact. The result is not always optimal, but it is fast and simple, and the loss is usually negligible.
The common pattern:
- Build ordinary Huffman lengths.
- Clamp every length above L down to L. The Kraft sum is now above 1.
- Repay the overflow by lengthening some codes shorter than L, starting with the least frequent ones (moving a code from length k to k + 1 frees 2^(−k−1)). Repeat until the sum is ≤ 1.
zlib applies this idea to its per-length counts: for each overflowing leaf, it finds a shorter leaf, pushes it down one level, and attaches the overflow leaf beside it. JPEG's reference procedure (ITU T.81, Annex K.3) works the same way on the BITS array, the count of codes at each length. It repeatedly takes two symbols from the longest length, moves one up to sit beside a code moved down from a shorter length, and continues until nothing exceeds 16 bits.
Gotchas and Edge Cases
- Impossible limits. If 2^L < n, no prefix code exists. Check this and raise an error before running any algorithm.
- Zero-frequency symbols. Remove them before limiting. DEFLATE marks an unused symbol with length 0, which takes no code space.
- A single used symbol. Give it length 1. DEFLATE decoders accept one distance code of length 1 for this case.
- Incomplete codes. A heuristic can leave the Kraft sum below 1. Some decoders, including the strict checks in zlib's inflate, reject over-subscribed codes and most incomplete ones, so the safe target is a sum of exactly 1 whenever n ≥ 2.
- Ties. Different tie-breaking can produce different but equally optimal lengths. Canonical assignment makes the final codes deterministic once the lengths are fixed.
Choosing an Approach
| Situation | Recommended method |
|---|---|
| Huffman max length already ≤ L (the usual case) | Use the Huffman lengths unchanged |
| You need guaranteed optimal cost under a limit | Package-merge, O(nL) |
| Speed-critical encoder with a large alphabet | Heuristic repair |
| JPEG encoder | Annex K procedure, including the dummy symbol |
In practice, check the maximum length first. Most real inputs never exceed the limit, so the limiting step only runs on unusual data.
Exercise
An alphabet has 300 used symbols and you want a maximum code length of 8 bits. Can a length-limiting algorithm produce valid lengths? What is the smallest workable limit?
Show answer
No. There are only 2^8 = 256 distinct 8-bit patterns, so at most 256 symbols fit, and the Kraft sum would exceed 1. The smallest limit is 9 bits, since 2^9 = 512 ≥ 300.
Exercise
A heuristic clamped some lengths and produced {a: 1, b: 2, c: 3, d: 3, e: 3}. Compute the Kraft sum and say what must change.
Show answer
The sum is 1/2 + 1/4 + 3 × 1/8 = 1.125, which exceeds 1, so no prefix code exists. Overflow of 1/8 must be repaid. For example, lengthen b from 2 to 3. That frees 1/8 and gives {a:1, b:3, c:3, d:3, e:3} with sum exactly 1.
Exercise
Run packagemerge on the Fibonacci frequencies with maxlen set to 3. What happens, and why?
Show answer
It raises ValueError, because 2^3 = 8 equals the 8 symbols, so the check passes and every symbol gets exactly 3 bits (Kraft sum 1). It does not raise. The cost is 54 × 3 = 162 bits, compared with 135 for L = 4 and 132 for unlimited Huffman. A tighter limit forces frequent symbols to give up short codes.