Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Greedy

Frequent Symbols, Short Codes.

Don't memorize Huffman coding — watch the tree assemble itself. To compress text you want frequent symbols to have short codes and rare ones long codes, with no code a prefix of another so the bitstream decodes cleanly. Huffman builds the optimal such code greedily: repeatedly merge the two least-frequent nodes with a min-heap until a single tree remains, then read each code off its root-to-leaf path.

prefix-free · merge the two smallest · min-heap · left 0 / right 1
PREFIX-FREE

No code is a prefix of another, so a stream of bits decodes with no separators.

FREQUENCY

Common symbols deserve short codes; rare ones can afford to be long.

GREEDY MERGE

Combine the two lowest-frequency nodes into a parent; repeat. A min-heap finds them fast.

READ THE TREE

Walk from the root: left is 0, right is 1. Each leaf's path is its code.

huffman.sim — a:5, b:2, c:1, d:1
Ready

Four symbols with frequencies a:5, b:2, c:1, d:1. Each starts as a leaf. Press Step to greedily merge the two lowest-frequency nodes, over and over, until one tree remains — then read the codes.

merge the two smallest weights → parent weight = sum · repeat
0
Merges
—
Encoded bits

Greedy, and provably optimal

Most greedy algorithms give a decent answer that is not always the best. Huffman is the rare greedy that is provably optimal. Start with one leaf per symbol, weighted by frequency, all sitting in a min-heap. Pull the two smallest, join them under a new parent whose weight is their sum, and drop that parent back in the heap. Repeat until a single tree remains. Why is grabbing the two smallest each time optimal? An exchange argument: in any optimal prefix code the two least-frequent symbols can be moved to be the two deepest sibling leaves without increasing the cost — so building them in as the first, deepest merge never closes off the best solution. The resulting tree minimizes the total encoded length, the sum of each frequency times its depth. For a:5, b:2, c:1, d:1 that comes to just 15 bits versus 18 for a flat two-bit code.

01

One leaf per symbol

Weight each symbol by its frequency and put them all in a min-heap (a priority queue).

02

Merge the two smallest

Pop the two lowest weights, join them under a parent of weight = their sum, push it back.

03

Repeat to one tree

Each merge removes two nodes and adds one, so after n−1 merges a single tree is left.

04

Read the codes

Label edges 0 (left) and 1 (right); each leaf's path is its codeword. Total bits = Σ freq·depth.

Time
O(n log n)
Space
O(n)
Result
Optimal prefix code
Engine
Greedy + heap

Because only leaves hold symbols, every codeword ends at a leaf and can never begin another — that is the prefix-free property, for free. Huffman is the entropy-coding stage inside DEFLATE (zip, gzip, PNG), JPEG and MP3. It leans directly on the priority queue to keep pulling the smallest, and it sits beside Kruskal and Dijkstra in the greedy family — take the locally best choice, and here that choice is provably globally best.

Check yourself

1 · What does Huffman merge at each step?

Popping the two smallest weights from a min-heap and joining them pushes the rarest symbols deepest, which is exactly what an optimal code needs.

2 · Why must the code be prefix-free?

If no codeword is a prefix of another, the decoder knows a symbol is complete the moment its bits end — only leaves carry symbols, so this always holds.

3 · Why is Huffman's greedy choice optimal?

You can rearrange any optimal code so the two least-frequent symbols are deepest siblings without raising the cost, so merging them first never loses optimality.

The picture: the tree and its codes

0a 45100c 121b 1325100f 51e 9141d 163055100010010111001101111cost = 45·1 + 13·3 + 12·3 + 16·3 + 9·4 + 5·4 = 224 bits
The tree built from frequencies a 45, b 13, c 12, d 16, e 9, f 5 (a total of 100). Leaves are highlighted and their codewords sit underneath. The frequent symbol a gets one bit; the two rarest, f and e, get four.

Worked example, step by step

Take six symbols with frequencies a:45 b:13 c:12 d:16 e:9 f:5, 100 characters in total. A flat code needs 3 bits per symbol, 300 bits overall. At each step pop the two smallest weights, join them, push the sum back, and add the new weight to a running cost.

StepMerge the two smallestNew weightRunning costHeap afterwards
1f:5 + e:9141412, 13, 16, 45, 14
2c:12 + b:13253914, 16, 45, 25
3node 14 + d:16306925, 45, 30
4node 25 + node 305512445, 55
5a:45 + node 55100224100
doneone tree of weight 100—224100

The running cost is the encoded size: each merge pushes every symbol beneath it one level deeper, so adding its weight adds one bit per occurrence. The final 224 equals the sum of frequency times depth read off the tree (45·1 + (13+12+16)·3 + (9+5)·4), which is 74.7% of the 300 bits a flat code would use. The first merge, f with e, makes the deepest pair, and that is the exchange argument in action: the rarest symbols belong at the bottom. The frequent symbol a is never merged until the last step, which is why it ends up one bit from the root.

Complexity and trade-offs

CaseTimeSpaceWhy
Huffman with a binary heapO(n log n)O(n)n − 1 merges, each two pops and a push at O(log n). Here n is the number of distinct symbols, not the length of the data.
Huffman, input already sortedO(n) after sortingO(n)Two queues replace the heap: the original leaves and the merged nodes both arrive in non-decreasing order, so the two smallest are always at a front.
Fixed-length codeO(1) per symbolO(1)Needs ⌈log₂ n⌉ bits per symbol: 300 bits for this example, against 224 for Huffman (2.24 bits per symbol on average against 3).
Encoding / decodingO(L) in the data lengthO(n) for the treeEncode by table lookup; decode by walking bits from the root to a leaf. The walk is per bit, so decoding is linear in the compressed size.
Entropy limit——The Shannon entropy of these frequencies is 2.220 bits per symbol, so no symbol-by-symbol code can average below it. Huffman reaches 2.24 here.

Huffman is optimal among codes that assign each symbol a whole number of bits, and it is within one bit per symbol of the entropy. The gap can still hurt: a symbol that deserves 0.1 bits must be given at least one. Arithmetic coding and asymmetric numeral systems remove that rounding by sharing fractional bits across symbols, at the cost of more arithmetic per symbol. You also pay to send the tree, or a canonical list of code lengths, in front of the data, so on tiny inputs the header can outweigh the saving.

Common mistakes

  • Putting unorderable nodes in the heap

    Pushing (freq, node) tuples works until two frequencies tie, then Python compares the nodes themselves: heapq on [(1, {"x": 1}), (1, {"y": 2})] raises TypeError. Add a unique counter as the second tuple element so ties never reach the node.

  • Giving a one-symbol input an empty code

    For the string "aaaa" the tree is a single leaf with no edges, so its path is the empty string and the whole message encodes to zero bits, which no decoder can read back. Give a lone symbol a 1-bit code, or store the symbol and the count.

  • Letting encoder and decoder break ties differently

    With frequencies a:1 b:1 c:2 d:2, two valid tie-breaks give different codes, {'a': '00', 'b': '01', 'c': '10', 'd': '11'} and {'c': '0', 'b': '100', 'a': '101', 'd': '11'}, yet the same cost, 12 bits each. Both are optimal, but a stream written with one and decoded with the other is garbage. Send the code lengths and rebuild canonically, or ship the tree.

  • Summing depths without weights

    Total bits is Σ freq · depth. Summing only depths, or averaging code lengths, treats the 5-count symbol like the 45-count one. On the example above the plain depth sum is 18, not 224.

  • Expecting it to beat entropy on skewed data

    For two symbols with probabilities 0.99 and 0.01, every code must give each symbol at least one bit, so Huffman spends 1 bit per symbol while the entropy is 0.081 bits. Long runs of one symbol compress far better with run-length or arithmetic coding.

Where this shows up

  • Canonical codes in compressed formats

    DEFLATE does not store the tree. It stores only the length of each symbol’s code and rebuilds the same codes from the lengths, which is why encoder and decoder never disagree about ties. Brotli and the literal stage of Zstandard use Huffman codes too.

  • Optimal merge order

    Merging sorted files costs the sum of the sizes merged, and merging the two smallest first minimises that total. It is the identical greedy and the identical heap, with file sizes in place of frequencies.

  • Hierarchical softmax

    Large-vocabulary word models have used a Huffman tree over words so that frequent words have short paths and a prediction needs only a few binary decisions instead of one per word in the vocabulary.

  • Interview shape

    The pattern “repeatedly take the two smallest from a priority queue and push back a combination” also solves rope-joining and stone-merging cost questions. Recognising it is most of the work.

SOLVE IT YOURSELF

Solve it: the cost of an optimal code

Give frequent symbols short codes and rare ones long codes, and you get the provably smallest prefix-free encoding. The greedy that finds it is four lines. Python or TypeScript, running for real in your browser.

YOUR TASK

Implement huffman_cost(freqs): given symbol frequencies, return the total bits of the optimal Huffman encoding. Repeatedly merge the two smallest weights and accumulate each merge cost.

HINTS — 6 IDEAS
  1. Repeatedly take the two smallest weights, merge them into one node of weight a + b, and push it back.
  2. Add a + b to a running total on every merge. That total is exactly the encoded size in bits.
  3. Why: each merge pushes both subtrees one level deeper, adding one bit to every symbol underneath — so summing the merge weights sums every symbol’s frequency × depth.
  4. A min-heap makes each merge O(log n); the whole thing is O(n log n).
  5. Two edge cases the tests check: an empty input costs 0, and a single symbol still needs 1 bit per occurrence — the loop never runs, so handle it explicitly.
  6. Ties can be broken either way and produce different trees, but always the same total cost — which is why this returns cost rather than the codes.
CPython · WebAssembly

Questions

Huffman vs a fixed-width code?

A fixed-width code uses ⌈log₂ k⌉ bits for every symbol. Huffman gives shorter codes to frequent symbols, so when the frequencies are skewed the average length drops — and it is the optimal prefix code with whole-bit codewords. For a:5, b:2, c:1, d:1 it needs 15 bits instead of 18.

Where is it actually used?

As the entropy-coding stage in DEFLATE (zip, gzip, PNG), JPEG and MP3. The earlier stages model or transform the data; Huffman (or a close relative) squeezes the final symbol stream.

Can you beat Huffman?

Only by leaving whole-bit codewords behind. Arithmetic and range coding assign effectively fractional bits per symbol and can compress slightly better, at more computational cost. Among integer-length prefix codes, Huffman is optimal.

The greedy that is always right.

Merge the two rarest, over and over, until one tree stands — then read the codes off its branches. Provably the shortest prefix code there is.

Finished this one? 0 / 99 Algorithms done
NextGreedy vs Dynamic Programming: When Is Greedy Safe? Next on the “When greedy is provably enough” ladder · rung 3 of 3

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms