TExcelTAD

Prefix Codes and Huffman's Algorithm

A file of 100,000 characters drawn from seven symbols needs 3 bits per character with a fixed-length code, 300,000 bits in all. But if some symbols are far more common than others, giving them shorter codewords, and the rare ones longer, can save a lot. The question is how to choose the lengths so the file can still be decoded and the total is as small as possible. In 1952 David Huffman, then a student, found a greedy algorithm that is exactly optimal. It is still inside ZIP, gzip, PNG and JPEG. This lesson builds the algorithm; the next one proves it optimal.

Prefix codes

A binary code assigns a bit string (codeword) to each symbol. A code is a prefix code if no codeword is a prefix of another. Prefix codes decode without separators: read bits until they spell a codeword, output its symbol, and start again. No ambiguity can arise, because no codeword could have continued into a longer one.

A prefix code is the same thing as a binary tree whose leaves are the symbols: the codeword of a symbol spells the path from the root, 00 for left and 11 for right. The length of a codeword is the depth of its leaf. With c.freqc.\mathit{freq} the frequency of symbol cc and dT(c)d_T(c) its depth in tree TT, the number of bits to encode the file is

B(T)=∑c∈Cc.freq⋅dT(c).B(T) = \sum_{c \in C} c.\mathit{freq} \cdot d_T(c).

An optimal tree is always full: every internal node has two children. Otherwise a node with one child could be replaced by that child, shortening every codeword below it.

The running example, a file of 100 characters (multiply by 1000 for the large file):

symbol A B C D E F G
frequency 21 9 16 4 30 8 12

Huffman's algorithm

Start with one single-node tree per symbol, weighted by its frequency. Repeatedly take the two trees of smallest weight, make them the two children of a new root, and give the new tree the sum of their weights. After n−1n - 1 merges one tree remains: the code.

text
HUFFMAN(C)                         // C: symbols with frequencies, n = |C|
1  Q = a min-priority queue of the symbols, keyed by freq
2  for i = 1 to n - 1
3      x = EXTRACT-MIN(Q)
4      y = EXTRACT-MIN(Q)
5      z = new node with left = x, right = y, freq = x.freq + y.freq
6      INSERT(Q, z)
7  return EXTRACT-MIN(Q)           // the root

The greedy choice is in lines 3 and 4: the two least frequent symbols are joined first, so they end up deepest. Each merge does three heap operations of O(lg⁡n)O(\lg n) (Priority Queues), so the algorithm runs in O(nlg⁡n)O(n \lg n).

python · try it yourself
import heapq
from itertools import count

freq = {"A": 21, "B": 9, "C": 16, "D": 4, "E": 30, "F": 8, "G": 12}

def huffman(freq):
    tie = count()                     # breaks ties between equal weights in insertion order
    heap = [(f, next(tie), sym) for sym, f in freq.items()]
    heapq.heapify(heap)
    while len(heap) > 1:
        fx, _, x = heapq.heappop(heap)
        fy, _, y = heapq.heappop(heap)
        print(f"merge {fx:3} + {fy:3} -> {fx + fy:3}   ({x} | {y})")
        heapq.heappush(heap, (fx + fy, next(tie), (x, y)))
    return heap[0][2]

def codewords(tree, prefix="", table=None):
    table = {} if table is None else table
    if isinstance(tree, str):
        table[tree] = prefix or "0"
    else:
        codewords(tree[0], prefix + "0", table)
        codewords(tree[1], prefix + "1", table)
    return table

tree = huffman(freq)
code = codewords(tree)
for sym in sorted(code, key=lambda s: (len(code[s]), code[s])):
    print(f"{sym}: freq {freq[sym]:2}  code {code[sym]}")
bits = sum(freq[s] * len(code[s]) for s in freq)
print("total bits:", bits, " fixed-length 3-bit code:", 3 * sum(freq.values()))
merge   4 +   8 ->  12   (D | F)
merge   9 +  12 ->  21   (B | G)
merge  12 +  16 ->  28   (('D', 'F') | C)
merge  21 +  21 ->  42   (A | ('B', 'G'))
merge  28 +  30 ->  58   ((('D', 'F'), 'C') | E)
merge  42 +  58 -> 100   (('A', ('B', 'G')) | ((('D', 'F'), 'C'), 'E'))
A: freq 21  code 00
E: freq 30  code 11
B: freq  9  code 010
G: freq 12  code 011
C: freq 16  code 101
D: freq  4  code 1000
F: freq  8  code 1001
total bits: 261  fixed-length 3-bit code: 300

The two rarest symbols, D (4) and F (8), are merged first and end up with the longest codewords; E and A, the two most common, get 2-bit codes. The tie counter makes the result deterministic: when two weights are equal, the tree inserted first is taken first. Different tie rules can give different trees, but always with the same total, here 261 bits against 300 for the fixed-length code, a saving of 13 percent.

Notice that the merge weights add up to the cost: 12+21+28+42+58+100=26112 + 21 + 28 + 42 + 58 + 100 = 261. Every merge of weights xx and yy pushes all the symbols in both trees one level deeper, which costs exactly x+yx + y more bits, so

B(T)=∑merges zz.freq.B(T) = \sum_{\text{merges } z} z.\mathit{freq}.

That identity makes the cost of a Huffman code computable without building the tree, which is what the practice problem Huffman Code Length asks for.

Encoding and decoding

python · try it yourself
import heapq
from itertools import count

def huffman_code(freq):
    tie = count()
    heap = [(f, next(tie), sym) for sym, f in freq.items()]
    heapq.heapify(heap)
    merged = 0
    while len(heap) > 1:
        fx, _, x = heapq.heappop(heap)
        fy, _, y = heapq.heappop(heap)
        merged += fx + fy
        heapq.heappush(heap, (fx + fy, next(tie), (x, y)))
    table = {}
    def walk(t, prefix):
        if isinstance(t, str):
            table[t] = prefix or "0"
        else:
            walk(t[0], prefix + "0"); walk(t[1], prefix + "1")
    walk(heap[0][2], "")
    return heap[0][2], table, merged

text = "abracadabra alakazam"
freq = {ch: text.count(ch) for ch in sorted(set(text))}
tree, table, merged = huffman_code(freq)
encoded = "".join(table[ch] for ch in text)
print("frequencies:", freq)
print("code:", table)
print("encoded:", encoded)
print(len(encoded), "bits; sum of merge weights:", merged, "; 8-bit ASCII would need", 8 * len(text))

decoded, node = [], tree
for bit in encoded:                     # walk down the tree; emit a symbol at each leaf
    node = node[int(bit)]
    if isinstance(node, str):
        decoded.append(node)
        node = tree
print("decoded:", "".join(decoded))
frequencies: {' ': 1, 'a': 9, 'b': 2, 'c': 1, 'd': 1, 'k': 1, 'l': 1, 'm': 1, 'r': 2, 'z': 1}
code: {'a': '0', 'd': '1000', 'k': '1001', 'l': '1010', 'm': '1011', 'z': '1100', 'b': '1101', 'r': '1110', ' ': '11110', 'c': '11111'}
encoded: 0110111100111110100001101111001111001010010010110001011
55 bits; sum of merge weights: 55 ; 8-bit ASCII would need 160
decoded: abracadabra alakazam

The decoder walks one edge per bit and restarts at the root after each leaf, which is the prefix property at work. Real compressors do not store the tree itself; they send only the codeword lengths and rebuild a canonical code from them, and they decode with lookup tables of several bits at a time instead of a bit-by-bit walk.

In C++

The cost of a Huffman code with std::priority_queue turned into a min-heap by std::greater. Only the weights matter for the total, so no tree is built.

cpp · try it yourself
#include <cstdio>
#include <functional>
#include <queue>
#include <vector>

long long huffman_bits(const std::vector<long long>& freqs) {
    if (freqs.size() == 1) return freqs[0];          // a single symbol still needs a 1-bit code
    std::priority_queue<long long, std::vector<long long>, std::greater<long long>> q(freqs.begin(), freqs.end());
    long long total = 0;
    while (q.size() > 1) {
        long long x = q.top(); q.pop();
        long long y = q.top(); q.pop();
        total += x + y;                              // every symbol below gets one bit longer
        q.push(x + y);
    }
    return total;
}

int main() {
    std::printf("%lld\n", huffman_bits({21, 9, 16, 4, 30, 8, 12}));
    std::printf("%lld\n", huffman_bits({1, 1, 1, 1, 1, 1, 1, 1}));
    std::printf("%lld\n", huffman_bits({1, 2, 4, 8, 16, 32}));
    std::printf("%lld\n", huffman_bits({1000000000, 1000000000, 1000000000}));
}
261
24
119
5000000000

Eight equal frequencies give a perfectly balanced tree, 3 bits each. Powers of two give the most lopsided tree possible, a "caterpillar" where each merge absorbs one new symbol. The last line needs 64-bit arithmetic.

Note: Huffman coding is optimal among codes that assign a whole number of bits to each symbol. Its average length per symbol is always within one bit of the entropy of the frequency distribution, the absolute lower bound for any lossless code; arithmetic coding gets closer by not rounding to whole bits. See Information Theory for the entropy bound, and the DSA lesson Huffman Coding for a first, informal look.

Test yourself

Which set of codewords is a prefix code?

  1. 0, 01, 11
  2. 1, 10, 100
  3. 0, 10, 110, 111
  4. 00, 0, 11

Huffman's algorithm on frequencies 5, 7, 10, 15: which two weights are merged first, and which second?

  1. 5 + 7, then 10 + 12
  2. 5 + 7, then 10 + 15
  3. 10 + 15, then 5 + 7
  4. 5 + 15, then 7 + 10

Merging trees of weights 9 and 12 adds how many bits to the total encoding length?

  1. 9
  2. 12
  3. 21
  4. 108

Why is an optimal prefix-code tree always full (every internal node has two children)?

  1. Because Huffman's algorithm builds it that way
  2. Because a node with one child could be replaced by its child, shortening the codewords below and lowering the cost
  3. Because codewords must have equal length
  4. Because full trees are balanced