Extended Science

Huffman coding

Definition

Giving frequent symbols short codes and rare ones long ones: the optimal prefix code, and why compression works at all.

Core rule: Used for instant lossless compression, and as the final stage in encoding pipelines like JPEG, ZIP, and HTTP; more broadly, it demonstrates the effort-saving principle of "allocate resources by frequency."

Say you're sending a friend a message written in zeros and ones. You give the most common symbol a single zero and another symbol the code zero one. When your friend sees the first zero, how do they know whether to stop?

Huffman coding gives different symbols different lengths, often leaving the shortest routes for the most common symbols. Among codes you can read one symbol at a time without guessing where it ends, it gets the shortest average length. Let's take the classroom problem that started it and work through three symbols.

How it works

Robert Fano gave his students at MIT the option of writing a term paper. David Huffman chose a problem about writing messages in binary. He knew how likely the messages were, and he had to use as few bits as possible on average. The receiver still had to tell where each message ended.

Picture the code as directions through a branching hallway. At each junction, a zero sends you left and a one sends you right. Rooms sit at the ends of the paths, so once you reach a room you know that symbol is complete and can return to the entrance.

  1. 01 · Count frequencies First, calculate how often each symbol appears.
  2. 02 · Merge lowest frequencies Repeatedly merge the two lowest-frequency nodes, building the tree bottom-up.
  3. +2 more mechanism steps & animation in the app

When it fails & limits

That gives you the shortest average within a particular kind of code, and there are several ways the larger bill can look different.

✦ Unlock full lesson in ConceptFlow

Unlock the full Huffman coding lesson in ConceptFlow

You’ve read the core idea and opening case. Get the ConceptFlow app to continue through the full breakdown, failure modes, 5-minute audio lesson, and decision practice.

  • ▸5-minute English & Mandarin audio lesson
  • ▸4 more deep-dive case & mechanism insights
  • ▸All 5 failure boundaries & counter-examples
  • ▸4-point decision checklist + 6-step practice

Tap a store button on mobile, or scan with your phone camera on desktop.