Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Huffman Coding

Optimal prefix codes by repeatedly merging the two rarest symbols.

In 1951 David Huffman, a graduate student in Robert Fano's information theory course at MIT, chose a term paper over the final exam and found what the Shannon–Fano method had missed: an optimal prefix code. His algorithm fits in four lines: repeatedly merge the two rarest symbols. Proving that this tiny greedy is optimal is a model exchange argument.

What you’ll learn

  • Model prefix codes as binary trees, and use Kraft's inequality to decide which codeword lengths are possible.
  • Run Huffman's algorithm and prove it optimal with an exchange lemma and a reduction lemma.
  • Implement it in O(nlog⁡n)O(n \log n) time with a heap, or O(n)O(n) with two queues when the frequencies are sorted.
  • Prove H≤L<H+1H \le L < H + 1, and explain how block coding, arithmetic coding and ANS get closer to the entropy HH.
  • Explain canonical Huffman codes and length limits, as used in DEFLATE.

Prefix codes are binary trees

A binary code assigns each symbol ii of an alphabet a bit string, its codeword, of length ℓi\ell_i. The code is a prefix code if no codeword is a prefix of another; then a decoder reads bits until they spell a codeword, outputs its symbol and starts again, with no separators needed.

Prefix codes are exactly binary trees with the symbols at the leaves: a left edge is a 0, a right edge a 1, and a symbol's codeword spells its path from the root, so ℓi\ell_i is its depth. With symbol probabilities pip_i (or counts), the expected cost in bits per symbol is

L=∑ipi ℓi.L = \sum_i p_i\,\ell_i .

Why. A codeword cc of length ℓ\ell owns the interval of binary fractions that start with 0.c0.c, of length 2−ℓ2^{-\ell}; for a prefix code these intervals are disjoint subsets of [0,1)[0, 1), so their lengths sum to at most 1. Conversely, give the codewords in order of increasing length the next free interval of the right size: dyadic intervals laid end to end never overlap.

An optimal tree is full: if an internal node had a single child, contracting that edge would shorten every codeword below it. A full tree satisfies Kraft with equality.

Check your understanding

Which list can be the codeword lengths of a binary prefix code?

  1. 1, 2, 2, 3
  2. 1, 1, 2
  3. 2, 2, 2, 2, 2
  4. 1, 2, 3, 3
Show the answer

D. 1, 2, 3, 3

12+14+18+18=1\tfrac12 + \tfrac14 + \tfrac18 + \tfrac18 = 1, so a code exists, for example 0, 10, 110, 111. The other lists have Kraft sums 1.1251.125, 1.251.25 and 1.251.25: too many short codewords.

Huffman's algorithm, and why it is optimal

Huffman's algorithm (1952): start with one single-leaf tree per symbol, weighted by its frequency. Repeatedly remove the two lightest trees, join them under a new root whose weight is the sum of theirs, and put it back. After n−1n - 1 merges one tree remains, and it is the code.

DerivationProof: an exchange lemma and a reduction lemma
  1. before−after=(pa−px)(ℓa−ℓx) ≥ 0\text{before} - \text{after} = (p_a - p_x)(\ell_a - \ell_x)\ \ge\ 0

    Exchange. Let x,yx, y be the two least frequent symbols, and a,ba, b two sibling leaves at the maximum depth of an optimal full tree. Swapping xx with aa changes the cost by

  2. ∃ optimal T∗: x,y siblings in T∗\exists\ \text{optimal } T^*:\ x, y \text{ siblings in } T^*

    since pa≥pxp_a \ge p_x and ℓa≥ℓx\ell_a \ge \ell_x. Swapping yy with bb likewise. So some optimal tree has xx and yy as sibling leaves at maximum depth: the greedy-choice property.

  3. L(T)=L(T′)+px+pyL(T) = L(T') + p_x + p_y

    Reduction. Replace xx and yy by one new symbol zz with pz=px+pyp_z = p_x + p_y. A tree T′T' for the reduced alphabet becomes a tree TT for the original one by hanging xx and yy below the leaf zz; since ℓx=ℓy=ℓz+1\ell_x = \ell_y = \ell_z + 1,

  4. L(Huffman)=Lreduced∗+px+py ≤ L(T∗)L(\text{Huffman}) = L^*_{\text{reduced}} + p_x + p_y\ \le\ L(T^*)

    Induction. Removing x,yx, y from T∗T^* gives a reduced tree, so L(T∗)−px−pyL(T^*) - p_x - p_y is at least the reduced optimum, which Huffman's remaining merges achieve by induction on nn. Huffman merges xx and yy first, so its cost is the reduced optimum plus px+pyp_x + p_y:

Predict before you look

Four symbols have probabilities 0.4, 0.3, 0.2 and 0.1. What is the expected length of Huffman's code, in bits per symbol?

Show the answer

1.9 bits

Merge 0.1 and 0.2 into 0.3, then the two 0.3s into 0.6, then 0.4 and 0.6. The lengths are 1, 2, 3, 3, so L=0.4⋅1+0.3⋅2+0.2⋅3+0.1⋅3=1.9L = 0.4 \cdot 1 + 0.3 \cdot 2 + 0.2 \cdot 3 + 0.1 \cdot 3 = 1.9 bits, against 2 for a fixed-length code and an entropy of about 1.846 bits.

Building it fast, and the entropy bound

python
import heapq
from itertools import count

def huffman_code(freq):                     # freq: {symbol: count}, at least 2 symbols
    tie = count()                           # tie-breaker, so trees are never compared
    heap = [(f, next(tie), s) for s, f in freq.items()]
    heapq.heapify(heap)
    while len(heap) > 1:
        f1, _, a = heapq.heappop(heap)      # the two lightest trees
        f2, _, b = heapq.heappop(heap)
        heapq.heappush(heap, (f1 + f2, next(tie), (a, b)))   # internal node = pair
    code = {}
    def walk(node, bits):
        if isinstance(node, tuple):
            walk(node[0], bits + '0')
            walk(node[1], bits + '1')
        else:
            code[node] = bits
    walk(heap[0][2], '')
    return code

The n−1n - 1 merges cost O(log⁡n)O(\log n) each, so the tree takes O(nlog⁡n)O(n \log n) time; writing out the codewords costs their total length. On "rare letters get deeper" it returns codewords of the same lengths as the widget's (ties may be placed differently) and 68 bits in total. Symbols are assumed not to be tuples.

If the frequencies arrive sorted, the heap is unnecessary (van Leeuwen, 1976). When a merge combines the two smallest weights a≤ba \le b, every other weight is at least bb, so the next merge produces at least 2b≥a+b2b \ge a + b: merged weights come out in nondecreasing order. Keep the leaves in one queue and the merged trees in a second; the two lightest trees are always among the two fronts, and the whole construction takes O(n)O(n) time.

DerivationProof
  1. L−H=∑ipilog⁡2pi2−ℓi=∑ipilog⁡2piqi−log⁡2K ≥ 0L - H = \sum_i p_i \log_2 \frac{p_i}{2^{-\ell_i}} = \sum_i p_i \log_2 \frac{p_i}{q_i} - \log_2 K\ \ge\ 0

    Lower bound. Let K=∑j2−ℓj≤1K = \sum_j 2^{-\ell_j} \le 1 (Kraft–McMillan) and qi=2−ℓi/Kq_i = 2^{-\ell_i} / K, a probability distribution. Gibbs' inequality says ∑ipilog⁡2(pi/qi)≥0\sum_i p_i \log_2 (p_i / q_i) \ge 0, so

  2. LHuffman ≤ ∑ipi⌈log⁡21pi⌉ < ∑ipi(log⁡21pi+1)=H+1L_{\text{Huffman}}\ \le\ \sum_i p_i \Big\lceil \log_2 \frac{1}{p_i} \Big\rceil\ <\ \sum_i p_i \Big(\log_2 \frac{1}{p_i} + 1\Big) = H + 1

    Upper bound. The Shannon lengths ℓi=⌈log⁡2(1/pi)⌉\ell_i = \lceil \log_2 (1/p_i) \rceil satisfy 2−ℓi≤pi2^{-\ell_i} \le p_i, hence Kraft, so a prefix code with these lengths exists. Huffman is at least as good as that code:

The "+1" can be most of the cost. A source that emits a with probability 0.99 and b with probability 0.01 has entropy about 0.081 bits per symbol, yet every code for single symbols spends at least 1 bit per symbol. Coding blocks of kk symbols as single super-symbols gives kH≤Lk<kH+1kH \le L_k < kH + 1, that is, less than H+1/kH + 1/k bits per symbol: Huffman on pairs already brings this source down to about 0.515 bits per symbol.

Huffman in practice, and beyond

A decoder needs the code as well as the data. A canonical Huffman code fixes one specific code for given lengths: sort the symbols by (length, symbol), give the first one all zeros, and give each next symbol the previous codeword plus 1, shifted left with appended zeros whenever the length grows. Only the lengths need to be transmitted.

DEFLATE, the format inside zip, gzip and PNG, does exactly this (RFC 1951), and caps codeword lengths at 15 bits. A cap can make Huffman's own tree illegal; the optimal code under a maximum length LL comes from the package-merge algorithm of Larmore and Hirschberg (1990) in O(nL)O(nL) time, though compressors often use simpler heuristic fixes.

LengthSymbols in orderCanonical codewords
2e00
3␣ (space), r, t010, 011, 100
4a, d, g, l, p, s1010, 1011, 1100, 1101, 1110, 1111
The canonical code for the lengths of "rare letters get deeper" (the space sorts before the letters). It still costs 68 bits, and the receiver rebuilds it from the ten lengths alone.

Huffman is optimal only among codes that spend a whole number of bits on each symbol. Arithmetic coding encodes a whole message as one number in [0,1)[0, 1) and comes within a couple of bits of the message's information content log⁡2(1/P(message))\log_2 (1/P(\text{message})). Asymmetric numeral systems (ANS; Duda, 2009 and 2013) achieve the same compression at speeds close to Huffman decoding, and a table-based form of ANS is used in the Zstandard compressor.

Key takeaways

  • Prefix codes are binary trees with the symbols at the leaves, of cost ∑ipiℓi\sum_i p_i \ell_i; lengths are achievable iff ∑i2−ℓi≤1\sum_i 2^{-\ell_i} \le 1 (Kraft, and McMillan for all uniquely decodable codes).
  • Huffman merges the two lightest trees n−1n - 1 times. Optimality: the rarest two can be deepest siblings (exchange), and merging them shifts every cost by exactly px+pyp_x + p_y (reduction).
  • A heap gives O(nlog⁡n)O(n \log n) time; with sorted frequencies two queues give O(n)O(n), because merged weights are produced in nondecreasing order.
  • H≤L<H+1H \le L < H + 1: coding blocks of kk symbols brings this below H+1/kH + 1/k per symbol, and arithmetic coding and ANS remove the per-symbol rounding.
  • Canonical codes let DEFLATE transmit only the codeword lengths, which it limits to 15 bits; optimal length-limited codes come from package-merge.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why is the tree of an optimal prefix code always full, with every internal node having two children?

  1. If a node had a single child, contracting that edge would shorten every codeword below it and lower the cost
  2. Kraft's inequality forbids nodes with one child
  3. Huffman's algorithm only merges pairs, and only Huffman trees are optimal
  4. A prefix code must use every bit string of each length
Show the answer

A. If a node had a single child, contracting that edge would shorten every codeword below it and lower the cost

Contracting the edge to a lone child removes one bit from every codeword in that subtree and keeps the code prefix-free, so a tree with a unary node is never optimal (when the probabilities are positive).

Question 2

A source has entropy H=2.3H = 2.3 bits per symbol. Which of these could be the expected length of its Huffman code?

  1. 2.0 bits
  2. 2.35 bits
  3. 3.3 bits
  4. 3.4 bits
Show the answer

B. 2.35 bits

Huffman's expected length satisfies H≤L<H+1H \le L < H + 1, here 2.3≤L<3.32.3 \le L < 3.3. Only 2.35 lies in that range.

Question 3

In the reduction lemma, the two rarest symbols x,yx, y are merged into one symbol zz with pz=px+pyp_z = p_x + p_y. How do the cost of a tree T′T' for the reduced alphabet and the cost of the tree TT obtained by hanging x,yx, y below zz relate?

  1. L(T)=L(T′)+1L(T) = L(T') + 1
  2. L(T)=2 L(T′)L(T) = 2\,L(T')
  3. L(T)=L(T′)+px+pyL(T) = L(T') + p_x + p_y
  4. L(T)=L(T′)+pz ℓzL(T) = L(T') + p_z\,\ell_z
Show the answer

C. L(T)=L(T′)+px+pyL(T) = L(T') + p_x + p_y

Only xx and yy change: each sits one level below zz's old position, so together they cost (px+py)(ℓz+1)=pzℓz+px+py(p_x + p_y)(\ell_z + 1) = p_z \ell_z + p_x + p_y. Every reduced tree maps to a full tree this way at the same extra cost, which is why solving the reduced problem optimally solves the original.

Question 4

Why does the two-queue implementation build a Huffman tree in O(n)O(n) time when the frequencies are given in sorted order?

  1. Sorted frequencies always produce a balanced tree
  2. It merges equal weights without comparing them
  3. It needs a heap of size 2 only
  4. Merged weights come out in nondecreasing order, so both queues stay sorted and the two lightest trees are always at their fronts
Show the answer

D. Merged weights come out in nondecreasing order, so both queues stay sorted and the two lightest trees are always at their fronts

If a merge combines the two smallest weights a≤ba \le b, every remaining weight is at least bb, so the next merge creates a weight of at least 2b≥a+b2b \ge a + b. Appending merged trees to a second queue therefore keeps it sorted, and each step compares only the queue fronts.

Further reading

  • D. A. Huffman, "A method for the construction of minimum-redundancy codes," Proceedings of the IRE 40(9) (1952), 1098–1101.
  • T. M. Cover & J. A. Thomas, Elements of Information Theory, 2nd ed. (Wiley, 2006), chapter 5.
  • J. van Leeuwen, "On the construction of Huffman trees," Proceedings of the 3rd ICALP (1976), 382–410.
  • L. L. Larmore & D. S. Hirschberg, "A fast algorithm for optimal length-limited Huffman codes," Journal of the ACM 37(3) (1990), 464–473.
  • P. Deutsch, "DEFLATE Compressed Data Format Specification version 1.3," RFC 1951 (1996).