Sub topic 14
Length-Limited Huffman Codes
This chapter assumes you can build a Huffman tree from frequencies, read code lengths off it, and assign canonical codes from those lengths. It also uses the Kraft inequality: a prefix code with lengths l₁…lₙ exists exactly when the sum of 2^(−lᵢ) is at most 1.
Why Cap the Code Length?
Plain Huffman places no upper bound on code length. With skewed frequencies the tree can become a long chain. Frequencies that follow the Fibonacci sequence (1, 1, 2, 3, 5, 8, 13, …) give the worst case: n symbols produce a longest code of n − 1 bits.
Real formats set a hard limit for three reasons:
- Fast decoders look up the next k bits in a table with 2^k entries. A 30-bit code would need a table with a billion entries.
- Canonical code lengths are stored in the file header in a fixed number of bits, so their range has to be bounded.
- Decoders often keep bits in a 32- or 64-bit register, and a code must fit in that register.
| Format | Alphabet | Maximum code length |
|---|---|---|
| DEFLATE | Literal/length and distance codes | 15 bits |
| DEFLATE | Code-length codes (used for the header) | 7 bits |
| JPEG | DC and AC coefficient codes | 16 bits |
The Working Model
You want the cheapest set of lengths, measured as the sum of frequency × length, subject to two rules: every length is at most L, and the Kraft sum is at most 1. To avoid fractions, multiply the Kraft sum by 2^L. Each code of length l then uses 2^(L − l) "units", and the total must not exceed 2^L.
The algorithm called package-merge (Larmore and Hirschberg, 1990) solves this exactly in O(nL) time. Many encoders, including zlib, use a cheaper approach instead. They build a normal Huffman tree, clip any code that is too long, and then repair the Kraft sum. The sketch below follows that repair idea:
def limit_lengths(lengths, freq, max_len):
if len(lengths) > (1 << max_len):
raise ValueError("too many symbols for this length limit")
lengths = {s: min(l, max_len) for s, l in lengths.items()}
capacity = 1 << max_len
def kraft():
return sum(1 << (max_len - l) for l in lengths.values())
# Over budget: lengthen the rarest symbol that still has room.
while kraft() > capacity:
candidates = [s for s in lengths if lengths[s] < max_len]
s = min(candidates, key=lambda s: (freq[s], -lengths[s]))
lengths[s] += 1
# Under budget: spend leftover units on the most frequent symbols.
for s in sorted(lengths, key=lambda s: -freq[s]):
while lengths[s] > 1 and kraft() + (1 << (max_len - lengths[s])) <= capacity:
lengths[s] -= 1
return lengths
freq = {"a": 1, "b": 1, "c": 2, "d": 3, "e": 5, "f": 8, "g": 13}
huffman = {"a": 6, "b": 6, "c": 5, "d": 4, "e": 3, "f": 2, "g": 1}
def cost(lengths):
return sum(freq[s] * lengths[s] for s in lengths)
limited = limit_lengths(huffman, freq, 4)
print(limited) # {'a': 4, 'b': 4, 'c': 4, 'd': 4, 'e': 3, 'f': 3, 'g': 1}
print(cost(huffman), cost(limited)) # 78 80Clamping to 4 bits pushes the budget to 18 units out of 16. The repair loop lengthens e and then f. That leaves 1 unit of slack, and the second pass spends it by shortening e. The output costs 80 bits instead of 78, which is the best possible cost under a 4-bit limit here. The heuristic does not guarantee that result for every input. Package-merge does.
Common Errors
- Clamping without repairing. Clamped lengths often break the Kraft inequality. Canonical code assignment then produces codes longer than their stated length, or codes that are prefixes of other codes.
- A limit that is too small. n symbols need L ≥ ⌈log₂ n⌉. Without this check the repair loop runs out of candidates.
- Skipping the slack pass. After the repair loop, the code may leave part of the code space unused. Every unused unit costs bits.
Exercise
Frequencies a=1, b=1, c=2, d=4 give Huffman lengths 3, 3, 2, 1. Limit them to 2 bits. What lengths do you get, and how much does the total cost go up?
Show answer
Four symbols at 2 bits each use exactly 4 of the 4 available units, so the only valid result is a=2, b=2, c=2, d=2. The Huffman cost is 1·3 + 1·3 + 2·2 + 4·1 = 14 bits. The limited cost is 8·2 = 16 bits, an increase of 2 bits.