Huffman coding

Send a word with a flashlight using just two signals, 0 and 1. How short can you make it while keeping it readable?

Join the two lightest nodes. Their combined weight goes back in the queue. Repeat until one node remains.

Walk from the root to a letter. A left branch gives 0 and a right branch gives 1. Those bits form the letter’s code.

For k distinct symbols, building the tree takes O(k log k). The message length in bits is the sum of its letters’ code lengths.