Huffman Coding β€” Optimal Prefix Codes 🧩

Problem idea

Compress symbols with shorter codes for higher frequency

Given symbols with frequencies, build a prefix-free binary code that minimizes average code length. Huffman’s greedy method repeatedly merges the two least frequent nodes.

Greedy rule: pick two smallest frequencies Merge β†’ new node with sum frequency Left = 0, Right = 1
1make a min-heap of nodes (symbol, freq)
2while heap size > 1:
3 x = extractMin(); y = extractMin()
4 z = new node(freq = x.freq + y.freq)
5 z.left = x; z.right = y; insert z
6output codes by traversing tree (0/1)
Final codes
Codes appear when the tree is complete.
Symbol Frequency Code
Simulation
Pick two smallest β†’ merge β†’ repeat
Heap size = β€”
Picked: β€”
New node: β€”
Ready. Click Start.
Tree
Leaf nodes (symbols) and internal nodes (Ξ£) use different colors. Picked nodes are highlighted.
Merge log
Advanced (Optional): Try your own data
Add/remove symbols and try different frequencies. Minimum 2 symbols required.
Symbol Frequency Action
Sandbox: β€”