learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 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.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

Huffman Coding Calculator

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

Time: O(n log n)
Space: O(n)
Use Case: File compression (ZIP, PNG, JPEG, MP3), prefix codes
Showing the example graph for this algorithm.

4 symbols with their frequencies

Try:

Each different character becomes a symbol, counted (␣ is a space). Right-click a symbol to change its frequency.

Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Huffman Coding

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.

How it works

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.

Applications

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.

Pseudocode

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 s

The 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.

Worked example, step by step

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.

  1. Merge 1. f (5) and e (9) are the two lightest. They become the children of a new node of weight 14: f gets the bit 0 and e the bit 1.
  2. Merge 2. The lightest are now c (12) and b (13), not the new tree of weight 14. They join under a node of weight 25.
  3. Merge 3. The tree fe (14) and d (16) join under a node of weight 30. The codes of f and e now end in 00 and 01, the code of d in 1.
  4. Merge 4. cb (25) and fed (30) join under a node of weight 55. Every code inside gets one more bit in front: c and b now start with 0, f, e and d with 1.
  5. Merge 5. Only a (45) and the tree of weight 55 are left. a takes the bit 0 and gets the shortest code, the others get a leading 1. The root weighs 100, the length of the file.

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.

Complexity, and where it comes from

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.

When to use Huffman Coding, and when not to

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.

AlternativePrefer it whenCost
Fixed-length codeAll symbols are about equally frequent, or direct access by position matters more than size.O(1) per symbol
Shannon-Fano codingHistorical 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 codingSkewed 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 LZWThe data has repeated strings rather than skewed letter counts. In practice DEFLATE combines LZ77 with Huffman coding.O(message length)

Common pitfalls

  • Merging the wrong pair. The two lightest trees in the queue must be merged, including trees made by earlier merges. Merging the two least frequent original symbols each time, or always merging into the newest tree, gives a worse code.
  • Thinking the code is unique. Ties and the choice of which child gets 0 give different trees, and even different code lengths, with exactly the same total cost. The decoder needs the same tree, which is why formats such as DEFLATE send canonical codes rebuilt from the code lengths.
  • A single symbol. With only one distinct symbol the tree is a lone leaf and the path from the root is empty. Implementations must give it a 1-bit code by hand, as this page does.
  • Forgetting the code table. The decoder cannot guess the tree, so it has to be stored with the data. For a short message the table can cost more than the bits saved, and a fixed-length code is then smaller.

Frequently asked questions

What is Huffman coding?
A method of lossless data compression that gives frequent symbols short bit codes and rare symbols long ones. It builds a binary tree by repeatedly merging the two least frequent trees, and reads each symbol's code from the path between the root and the symbol. David Huffman published it in 1952.
Why is Huffman coding a greedy algorithm?
At every step it makes the locally best choice, merging the two lightest trees, and never reconsiders it. An exchange argument proves that this choice is always part of some optimal tree, so the greedy result is optimal among all prefix codes.
What is a prefix code?
A code in which no code word is the beginning of another. A decoder can then read the bits one by one and recognise each code word as soon as it ends, without separators. Every prefix code corresponds to a binary tree whose leaves are the symbols.
How do you calculate the bits saved by Huffman coding?
Multiply each symbol's frequency by the length of its code and add the results. Compare that total with the sum of the frequencies times the bits of a fixed-length code, the smallest whole number of bits that can number all the symbols. In the example on this page that is 224 bits against 300.
Is Huffman coding still used?
Yes. It is the entropy coding stage of DEFLATE (ZIP, gzip, PNG), of baseline JPEG and of MP3, and HTTP/2 uses a fixed Huffman code for headers. Newer formats often use arithmetic coding or asymmetric numeral systems where the extra compression is worth the cost.

Related algorithms: Kruskal's MST Algorithm, Prim's MST Algorithm, Prüfer Code, Bin Packing (First Fit Decreasing)

An example graph: you can change it, or start blank.

Zoom Controls

40%
Nodes: 6
Edges: 0