AlgoPlus//greedy / huffman
Read the theory

Huffman Coding

Build an optimal prefix code by repeatedly merging the two rarest symbols.

Trees in forest
Phase
Build tree
Your text (frequencies derived from it)
Legend
Leaf (character)
Merging
New parent
AI Tutor Workspace
In a nutshell
Huffman coding compresses text by giving frequent characters short bit-codes and rare ones longer codes. Starting from one leaf per character weighted by its frequency, it repeatedly merges the two lowest-frequency trees under a new parent until a single tree remains. Reading each character's path from the root (left = 0, right = 1) gives its code. Because the rarest symbols are merged in first, they end up deepest with the longest codes — and the result is provably the optimal prefix code. With a heap to pull the two smallest each round, it runs in O(n log n).
Ready
Press play to begin the cinematic walkthrough.
Give common symbols short codes and rare ones long codes. Merging the two rarest trees first pushes rare symbols deepest — which is provably the optimal prefix code.
Key terms
Go deeper in the lesson
Read the full theory, intuition & complexity for Huffman Coding.