Sri gives the message to the market bit codes: your message counted, the Huffman tree built from a queue that joins the two lightest, the codes read off the…
Why it matters
Huffman is inside ZIP, gzip, PNG, JPEG and MP3 (usually the last stage after LZ77 or another transform). A prefix-free code lets bits be read with no separators; a home-made code that is not prefix-free looks shorter but cannot be decoded.
The key idea
Letters only at the leaves
Common mistakes
My own variable-length code will not decode Its codes are not prefix-free: one code is the start of another (0 and 00), so the reader stops too early. Build the codes from a tree with letters only at its leaves, as Huffman does.
A short text barely saves, or even grows The receiver needs the code table, and that table is a fixed cost. For a short text it outweighs the saving. Huffman wins on long, patterned data (or with a fixed table, as DEFLATE allows).
I heard something beats Huffman Huffman is optimal only among whole-bit codes per letter. If one letter is very frequent it still needs 1 bit while its entropy is less. Arithmetic coding and ANS use "fractions of a bit" and approach the entropy.
Try it in this playground
Send the message Run Huffman until the message comes back whole.
A one-bit code Write a message with one very frequent letter, run to the end.
Write your message Type your own message under the scene.
Bagas’s code fails Use Bagas’s code to the end and watch the message come back wrong.