Huffman Coding
Huffman coding repeatedly merges the two least frequent symbols. The resulting binary tree assigns short codes to common symbols and long codes to rare ones.
The path for the current letter is highlighted. Left edges are 0, right edges are 1. Frequent letters get shorter codes, which is why the weighted bit count is far below 8 bits per symbol.
What you are seeing
Put every symbol in a priority queue keyed by frequency.
Remove the two smallest nodes and create a parent whose weight is their sum. Repeat until one tree remains.
Reading left as 0 and right as 1 gives each symbol a prefix-free code. No code is a prefix of another.
Why it matters
Huffman coding is used in ZIP, JPEG, MP3, and many network protocols. It is a compact demonstration of greedy algorithms and information theory.
Complexity & details
Building the tree with a heap: O(n log n) for n distinct symbols. Encoding and decoding are linear in the bit length.
Frequently asked questions
Why is the code prefix-free?+
Symbols live only at leaves. A complete code stops at a leaf, so it can never be a prefix of a longer code below it.
Does Huffman coding always reach the entropy limit?+
Not exactly. It is optimal among binary prefix codes for a known symbol distribution, but it can still be slightly above the Shannon entropy.