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.