Learning LabExplorable explanations
← All artifacts
Information Theory

Huffman Coding

Frequent letters deserve shorter codes. Type a string, merge the two rarest symbols again and again, and watch a Huffman tree grow whose codeword lengths land within a bit of the entropy floor.

huffmancompressionentropyinformation-theory
LiveInteractive · drag, toggle, run it
Information Theory · Compression

Huffman Coding

Spend fewer bits on the letters you use most and you can shrink text below its fixed-width size, with no separators marking where one code ends and the next begins. Huffman coding finds those codes by a stubbornly simple rule: count each character, then keep merging the two rarest nodes until one tree remains. Reading 0 for every left branch and 1 for every right gives each symbol a prefix-free codeword, no codeword the start of another, and it is provably as short as any such code can get.

English text: a handful of common letters dominate, so Huffman shaves real bits.

Build the tree
merge 0 of 26
Priority queue (lowest frequency first)
43
Press Step or Play to start merging the two lowest-frequency nodes.
The tree
Internal nodes show their combined frequency. The tree fills in merge by merge.
01010101010101010101010101010101010101010101010101014316842q00000i000012c00010k0001142b00100w001012n00110f00111842x01000j010012m01010p0101142s01100v011012l01110a01111271142z10000y100012d10010g100117e1010o101116space11084t11100h111014u11110r11111
Code table
SymbolFreqCodewordBitsTotal
space8
o4
e3
h2
r2
t2
u2
a1
b1
c1
d1
f1
g1
i1
j1
k1
l1
m1
n1
p1
q1
s1
v1
w1
x1
y1
z1

Finish building the tree to read off the codewords.

Huffman size
build the tree first
Fixed width baseline
215 bits
5 bits/symbol, 27 symbol alphabet
Compression vs fixed
Source entropy
4.39 bits
Shannon H, the theoretical floor
Why it works

The greedy merge is optimal. At each step the two least frequent symbols can be placed as deepest siblings without loss, because any optimal tree can be rearranged so they sit there. Merging them into one node of summed frequency and recursing on the smaller problem builds the shortest possible average code.

Prefix-free means uniquely decodable. Every symbol lives at a leaf, so no codeword is a prefix of another. A decoder walks the tree from the root, turning left on 0 and right on 1, and emits a symbol the instant it reaches a leaf. No commas, lengths, or escape characters are needed in the stream.

Entropy is the floor. The source entropy H is the average information per symbol. No prefix-free code can beat it, and Huffman gets within one bit of it. The gap shrinks toward zero when probabilities are close to powers of one half, or when you Huffman-code blocks of symbols at once.

Frequencies, tree, codewords, and entropy are computed live from your text. Ties break by insertion order so the tree is reproducible.