Huffman Coding

medium
Unit 17 · Greedy & Trees0/3 to milestone

Huffman coding builds an optimal prefix-free code: frequent symbols get short codes.

Implement:

  • huffman_codes(freqs): freqs maps symbols to positive counts. Push the leaves onto a min-heap in sorted symbol order as (freq, order, node), where order is an increasing counter that breaks ties. Repeatedly pop two nodes; the first popped becomes the left child (bit "0") and the second the right (bit "1"), and push their parent with the summed frequency and the next counter value. A single symbol gets the code "0". Return {symbol: code}.
  • encode(text, codes) and decode(bits, codes)
  • encoded_length(freqs, codes): the total bits, Σ freq × len(code)
#greedy#heaps#compression2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Huffman Coding · TechGradify