Information Theory/Huffman Coding
64 / 67

03/2021Information Theory

Huffman Coding

╌╌╌╌

Lossless text compression by Huffman coding. Frequent characters get short binary codes and rare ones long codes, and no code is a prefix of another, so the compressed stream decodes back to the original with no ambiguity.

The codes come from a binary tree built bottom up. Start with one leaf per character, keyed by its frequency, and repeatedly merge the two lowest-frequency nodes under a new parent whose frequency is their sum, until a single tree remains. Reading the tree root-to-leaf — 0 for a left branch, 1 for a right — gives each character its code.

Algorithm:Huffman(C)\textsc{Huffman}(C) — build an optimal prefix code from frequencies
  1. 1
    input: characters CC, each with frequency f[c]f[c]
  2. 2
    QQ \gets min-priority queue over CC, keyed by ff
  3. 3
    for i1i \gets 1 to C1\lvert C \rvert - 1 do
  4. 4
    xExtract-Min(Q)x \gets \textsc{Extract-Min}(Q)
  5. 5
    yExtract-Min(Q)y \gets \textsc{Extract-Min}(Q)
  6. 6
    zz \gets new node with children x,yx, y and f[z]f[x]+f[y]f[z] \gets f[x] + f[y]
  7. 7
    insert zz into QQ
  8. 8
    return Extract-Min(Q)\textsc{Extract-Min}(Q)
The Huffman tree for frequencies a:5 b:2 c:1 d:1 puts rare symbols deepest. Each internal node holds the summed frequency of its subtree; reading the 0/1 edge labels from the root to a leaf spells that symbol's code — a = 0, b = 10, c = 110, d = 111.

Because every symbol lands on a leaf, no codeword is a prefix of another, and the compressed stream needs no separators between symbols. Decoding walks the tree from the root, branching left on a 0 and right on a 1; the moment it reaches a leaf it emits that symbol and jumps back to the root. Each input bit is read once, so decoding is linear in the length of the stream.

The greedy choice turns out to be optimal, and the reason is structural. A prefix code is exactly a labeling where every character is a leaf, so no code sits on the path to another. The cost of a tree is the expected code length

where is the depth of leaf . Merging the two rarest symbols first is safe because they can always be pushed to the deepest level of some optimal tree without raising ; induction on the merges then gives a globally optimal code. No prefix code beats it.

The theoretical floor sits just below that. Shannon's source coding theorem sets the entropy

as the average number of bits per symbol no lossless code can undercut, where is the symbol's probability. Huffman coding lands within one bit of it,

the slack being the cost of using a whole number of bits per symbol when the ideal length is usually fractional. The gap shrinks to nothing when the probabilities are exact powers of , and it is amortized away in practice by coding blocks of symbols at once.

References

  1. Project repository
  2. Reference notes: Huffman Codes
  3. Reference notes: The Greedy Method

╌╌ END ╌╌