Guest
Sign in to keep your graphs and progress.

Practice book
Graph Theory Through Problems300 Exercises with Hints, Worked Algorithms and Complete Solutions
By Mohammed Islam Hadjoudj
Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.
Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on AmazonSelect an algorithm and generate steps to begin visualization
Short codes for frequent symbols
Builds the optimal prefix code for the symbols (vertices, frequency = the × number): joins the two lightest trees until one is left, then reads each code from the root
4 symbols with their frequencies
Each different character becomes a symbol, counted (␣ is a space). Right-click a symbol to change its frequency.
Select an algorithm and generate steps to begin visualization
Huffman coding turns symbols into bit strings so that a message takes as few bits as possible: frequent symbols get short codes and rare ones long codes. David Huffman found the method in 1952 as a student at MIT, in a term paper for Robert Fano's information theory course. The codes form a prefix code, which means that no code word is the beginning of another, so a stream of bits can be decoded without separators. Among all prefix codes for the given frequencies, Huffman's uses the fewest bits.
Every symbol starts as a one-node tree weighed by its frequency, and all the trees go into a priority queue. The algorithm takes out the two lightest trees, joins them under a new node whose weight is the sum of theirs, and puts the new tree back. After n - 1 merges one tree is left. Each symbol's code is read from the root down to it: 0 for the branch to the tree taken out first in a merge, 1 for the other. With a binary heap the merges take O(n log n) time. The visualizer draws the tree growing above the symbols, writes each bit on its branch and shows every code so far next to its symbol: each merge adds one bit in front.
Huffman codes are the last stage of DEFLATE, the compression in ZIP, gzip and PNG, and of JPEG and MP3, where they encode the output of the earlier steps. Fax machines used fixed Huffman tables, and HTTP/2 compresses headers with a static Huffman code. The algorithm is also the classic example of a greedy algorithm proved by an exchange argument, which is why it appears in every algorithms course, and its average code length is always less than one bit above the entropy, Shannon's lower bound.
Huffman coding is a greedy algorithm on a priority queue of trees. Each round removes the two lightest trees and puts back their union, so the queue shrinks by one tree per round until a single tree, the code tree, is left.
Huffman(symbols with frequencies f):
Q = priority queue of one-node trees, keyed by f
repeat n - 1 times:
x = Q.extractMin()
y = Q.extractMin()
z = new node with children x (bit 0) and y (bit 1)
f(z) = f(x) + f(y)
Q.insert(z)
root = Q.extractMin()
code(s) = the bits on the path from root to leaf sThe invariant behind the proof: after every round there is an optimal code tree in which each tree still in the queue appears as a subtree. It holds at the start, and an exchange argument shows that it survives every merge: in some optimal tree the two least frequent symbols are siblings at the deepest level, because swapping a deeper symbol with a more frequent, shallower one never increases the cost. The total cost equals the sum of the weights of all inner nodes, which is why merging the two lightest trees first is right.
Encode the six characters of a 100-character file, the example from Cormen, Leiserson, Rivest and Stein that this page loads. A fixed-length code needs 3 bits per character, 300 bits in all.
Example graph: Symbols and frequencies: a 45, b 13, c 12, d 16, e 9, f 5. The queue starts as f 5, e 9, c 12, b 13, d 16, a 45.
The code is a 0, c 100, b 101, f 1100, e 1101, d 111. The file now takes 45·1 + 12·3 + 13·3 + 5·4 + 9·4 + 16·3 = 224 bits instead of 300, 25% less, an average of 2.24 bits per character against an entropy of about 2.22 bits.
Time: O(n log n) · Space: O(n)
There are n - 1 merges, and each does two extractions and one insertion on a binary heap of at most n trees, O(log n) each, so the merges cost O(n log n). Building the first heap takes O(n). Reading the codes is one walk of the tree, with O(n) nodes, plus writing the code words, whose total length is the sum of the depths. If the frequencies arrive sorted, two plain queues replace the heap, one for the symbols and one for the merged trees, and the whole algorithm runs in O(n), because the merged trees come out in increasing weight.
Huffman coding is optimal among prefix codes that give each symbol a whole number of bits. Other methods win when that restriction or fixed frequencies do not fit.
| Alternative | Prefer it when | Cost |
|---|---|---|
| Fixed-length code | All symbols are about equally frequent, or direct access by position matters more than size. | O(1) per symbol |
| Shannon-Fano coding | Historical interest: it splits the sorted symbols from the top down and is not always optimal, which is exactly what Huffman fixed. | O(n log n) |
| Arithmetic coding | Skewed probabilities, where a symbol deserves less than one bit. It codes the whole message as one number and gets within a fraction of a bit of the entropy. | O(message length) |
| Adaptive Huffman (FGK, Vitter) | The frequencies are not known in advance, so the tree is updated as the symbols arrive. | O(code length) per symbol |
| LZ77 or LZW | The data has repeated strings rather than skewed letter counts. In practice DEFLATE combines LZ77 with Huffman coding. | O(message length) |
Related algorithms: Kruskal's MST Algorithm, Prim's MST Algorithm, Prüfer Code, Bin Packing (First Fit Decreasing)