Huffman Encoding Visualizer

Enter text to see how Huffman coding assigns shorter codes to frequent characters.

Loading interactive simulation...

Optimal Prefix-Free Entropy Encoding 🖖

Huffman encoding optimizes data compression by dynamically constructing a binary tree based on the statistical frequency of input symbols. It assigns mathematically shorter bit sequences to highly probable characters, achieving the theoretical limit of Shannon entropy. The strict requirement of prefix-free codes guarantees unambiguous algorithmic decoding. This deterministic reallocation of binary weight mathematically minimizes the total file size without any loss of data.

Built by always merging the rarest 🖖

The tree grows from the bottom up: list every character by how often it appears, then repeatedly glue the two least-frequent items into a small subtree and treat it as one bundle. Repeat until a single tree remains, then read each code by walking down from the top — left is 0, right is 1. This "greedy" habit of always combining the two smallest looks short-sighted, yet it provably produces the shortest possible codes.

A term paper that beat the professor 🖖

David Huffman devised this in 1951 as an MIT graduate student, when professor Robert Fano offered the class a choice between a final exam and a paper on finding the most efficient code. Fano and Claude Shannon had already tried, building their trees top-down. Huffman almost gave up, then realised building bottom-up — merging the rarest symbols first — was optimal, beating his own teacher's method.

Example problems

  • hello world - "hello world" → ~30% savings
  • mississippi - "mississippi" — high redundancy
  • uniform - "abcdef" — uniform distribution, minimal savings
  • single char - "aaaaaaaaaa" — trivial single-symbol case