What is Huffman coding?
A method of building, from the probabilities of the symbols, a prefix code whose average code length is as small as possible. A tree is built by repeatedly merging the two symbols (or nodes) with the smallest probabilities into one, and 0 and 1 are assigned at each branch to form the codewords. The more frequent a symbol, the shorter its codeword. It is optimal among prefix codes that code one symbol at a time, and its average code length is at least the entropy and less than the entropy + 1 bit. It is used in combination with other methods in Deflate (ZIP, gzip), JPEG and elsewhere. Huffman published it in 1952.
Japanese name: ハフマン符号
Huffman coding appears in 5 practice questions across 1 topic, including Information Theory and Coding Basics.
Field: Information Theory and Coding Basics
How to build one
For symbols with probabilities 1/2, 1/4, 1/8 and 1/8, first the two 1/8s are merged into 1/4, then that and the 1/4 into 1/2, and finally that and the remaining 1/2. Labeling the branches from the root to each symbol with 0 and 1 gives the codewords 0, 10, 110 and 111, with an average code length of 1.75 bits, equal to the entropy. When every probability is the reciprocal of a power of 2, the average code length matches the entropy like this.
The codewords are not unique
The codewords change depending on how 0 and 1 are assigned and on which of two equal probabilities is merged first. For example, with probabilities 0.4, 0.2, 0.2, 0.1 and 0.1 the code lengths can be 1, 2, 3, 4, 4 or 1, 3, 3, 3, 3 or 2, 2, 2, 3, 3, but the average code length is 2.2 bits in every case. This is why examinations tend to ask for the average code length rather than the codewords themselves.
FAQ
What is needed to restore data compressed with a Huffman code?
Restoring the data requires knowing which codeword was assigned to which symbol (a code table, or the code length of each symbol). Compressed data therefore carry the code table with them or use a table agreed in advance. Deflate sends only the code lengths, and the receiver rebuilds the codewords by the same rule (canonical Huffman codes).
Can a Huffman code make any data smaller?
No. If the symbol probabilities are not skewed, the data hardly shrink. For example, in data where all 256 byte values are equally likely, every codeword is 8 bits long, and the code table makes the result slightly larger.