All episodes · From a List to Your Map App · Episode 16

Short Codes for Common Letters: Huffman Coding

Pressing play loads the video from YouTube.

At eight bits per letter, "she sells sea shells" takes 160 bits. Give common letters short codes and rare ones long codes, and it takes just 49.
We count the letters, keep joining the two rarest into one (a greedy idea, with a heap doing the picking), and watch a tree grow. Zero on the left, one on the right: the path to each letter is its code. Then we turn the 49 bits back into the sentence, see why no separators are needed, and find Huffman coding inside zip files, PNG images and JPEG photos.

Every animation in this video is drawn by code, and the narration is an AI voice.

Transcript

She sells sea shells: twenty characters. At eight bits each, that's a hundred and sixty bits. Give common letters short codes and rare ones long codes, and the same sentence needs just forty-nine. Today: Huffman coding.

Back in season one, episode six, every letter took the same eight bits, common or rare. But in this sentence, s shows up six times, while a shows up just once.

Huffman's idea is greedy: take the two rarest, and join them into one, with their counts added. Then do it again. The two smallest are now three and three, then four and four, then six and six. Until only one is left: a tree, with the rarest letters deepest and the most common near the top. Grabbing the two smallest, again and again, is just the job for the heap from episode fourteen.

Now write a zero on every left branch, and a one on every right branch. The path from the top down to a letter is its code. s, e and l get two bits, the space gets three, h and a get four. Count by count, the whole sentence now takes forty-nine bits instead of a hundred and sixty.

And the bits split apart on their own, because no code is the start of another code. Start at the top, follow each bit down, and when you reach a letter, write it down and jump back up.

Zip files, PNG images and JPEG photos all use Huffman coding inside. The code table has to be saved too, but next to a long file, it's tiny.

Count the letters, join the two rarest, repeat. That greedy loop gives the shortest code you can get, letter by letter. Next time: finding a word in a long text, without checking the same letters over and over. See you there.

Next episode: finding a word in a long text without checking the same letters over and over.

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal