Kolton Ndoj

Huffman coding: short codes for common things

Inside most .zip files, PNG images and JPEG photos

What problem does it solve?

How can you store text in fewer bits without losing a single letter?

The big idea

Normal text spends 8 bits on every letter, whether it's a common 'e' or a rare 'z'. Huffman gives frequent symbols short codes and rare ones long codes, like Morse code making E a single dot. The genius move is building the code from the bottom up: repeatedly glue together the two rarest symbols into a team. No code is ever the start of another (it's 'prefix-free'), so the bits decode with no gaps or separators.

How it works, step by step

  1. 1. Count how often each symbol appears.
  2. 2. Put every symbol in a pile as a one-node tree weighted by its count.
  3. 3. Take the two lightest trees and join them under a new node whose weight is their sum.
  4. 4. Repeat until one tree remains.
  5. 5. Read each symbol's code from the path: left = 0, right = 1.

The key formula

H=−∑ipilog⁡2piH = -\sum_i p_i \log_2 p_i
pip_i
the fraction of the time symbol i appears
−log⁡2pi-\log_2 p_i
the ideal number of bits for symbol i: rarer means longer
HH
Shannon's entropy, the average bits per symbol that no lossless code can beat; Huffman stays within 1 bit of it

How fast is it?

Building the tree takes about k log k steps for k distinct symbols, which is tiny. It's lossless: you get back exactly what you put in. ZIP's DEFLATE first replaces repeated phrases with back-references (LZ77) and then Huffman-codes the result.

Try it yourself

Fun fact

David Huffman invented it in 1951 as an MIT student, and published it in 1952. His professor, Robert Fano, offered the class a choice between a final exam and a term paper on finding the most efficient binary code. Huffman nearly gave up, then found a method that beat the one Fano himself had worked on with Claude Shannon.

Related

Open it in the Math Lab →

Media · Intermediate