Algorithms · Huffman Coding and Optimal Merge Pattern
The Problem Being Solved
Suppose a file contains distinct symbols. Symbol occurs times, so the file has characters. We want to assign each symbol a binary codeword so that the file can be stored (or transmitted) in as few bits as possible, and so that the encoded stream can be decoded unambiguously.
Two ideas combine:
- Variable-length codes — give short codewords to frequent symbols, long codewords to rare ones.
- The prefix property — no codeword is a prefix of another codeword. This makes decoding possible without any separator characters.
Huffman's algorithm (David Huffman, 1952) builds the optimal prefix code for a given frequency distribution.
1.1 Fixed-length vs variable-length
With symbols, a fixed-length code needs bits per symbol. For that is bits per symbol, regardless of frequencies. A variable-length code can do better whenever the distribution is skewed.
1.2 The prefix property (definition)
A code is a prefix code (prefix-free code) if no codeword is a proper prefix of any other codeword.
- Valid: — no codeword starts another.
- Invalid: — is a prefix of , so the stream could be read as " then " or as "".
Key theorem (stated, not proved here): every prefix code corresponds to a binary tree whose leaves are the symbols, with left edge = 0 and right edge = 1; the codeword is the root-to-leaf path. Conversely every binary tree with leaves gives a prefix code. So designing an optimal prefix code = designing an optimal binary tree.
1.3 Cost formulas
Let = depth of leaf = length of codeword .
| Quantity | Formula | Meaning |
|---|---|---|
| Total encoded bits | size of the compressed file | |
| Average bits per symbol | , with | weighted path length |
| Entropy (lower bound) | for Huffman codes |
The quantity is also called the weighted external path length of the tree. Minimising it is exactly the goal.