Skip to content
StackDecode
GreedyAnimated

Huffman Coding

Repeatedly merge the two rarest symbols into a tree to get optimal prefix codes.

Time

O(n log n)

Extra space

O(n)

Use it for

Lossless compression.

How it works

  1. Count how often each letter appears.
  2. Repeatedly take the two lightest nodes and join them under a new parent whose weight is their sum.
  3. Continue until one tree remains. Going left appends 0 to a code, going right appends 1.
  4. Frequent letters end up near the root with short codes, rare ones deep with long codes. No code is the prefix of another, so decoding is unambiguous.

Watch it run

Loading animation…