Huffman coding calculator: build the tree and code table
Type a message, or a table of symbol frequencies, and this calculator builds the Huffman tree one merge at a time, then gives the code for every symbol, the encoded bits, and how many bits you save over fixed-length and ASCII codes. Step through each merge to check your own answer to a textbook exercise.
On this page
Huffman coding calculatorType a message, or symbols with their frequencies. Then step through the merges that build the tree.
- Two lightest trees, just merged
- New parent node
- Leaf (symbol)
Queue of trees (lightest first)
Size
What Huffman coding does
A fixed-length code gives every symbol the same number of bits: 8 bits per character in ASCII, or 3 bits each if a message only uses the letters a to f. Huffman coding, devised by David Huffman as a student in 1952, gives short codes to frequent symbols and longer codes to rare ones, like Morse code does. For a given set of symbol frequencies, no code that assigns each symbol its own fixed bit string produces a shorter encoding.
It is a prefix code: no code word is the beginning of another. That means an encoded bit string can be decoded without any separators. Read bits until they match a code word, output that symbol, and start again. The code words are exactly the root-to-leaf paths of a binary tree, with 0 for each left branch and 1 for each right branch, and the prefix property holds because symbols live only at leaves.
The algorithm
- Make one single-node tree per symbol, weighted by its frequency, and put them all in a priority queue.
- Remove the two trees with the smallest weights.
- Join them under a new parent whose weight is the sum of theirs, and put the new tree back in the queue.
- Repeat steps 2 and 3 until one tree is left. With symbols that takes merges.
- Label left branches 0 and right branches 1. Each symbol’s code is the path from the root to its leaf.
With a binary heap as the priority queue, each removal and insertion costs , so building the tree takes time. Counting the frequencies takes one pass over the message.
Worked example: abracadabra
- Count: a appears 5 times, b 2, r 2, c 1 and d 1, for 11 symbols in total.
- Merge c (1) and d (1) into a tree of weight 2. The queue is now b 2, r 2, {cd} 2, a 5.
- Merge b (2) and r (2) into weight 4. Ties are common; any choice among equal weights gives an optimal code.
- Merge {cd} (2) and {br} (4) into weight 6.
- Merge a (5) and the tree of weight 6 into the root, weight 11.
- Read off the codes:
a = 0,b = 110,r = 111,c = 100,d = 101. - Total: 5×1 + 2×3 + 2×3 + 1×3 + 1×3 = 23 bits, against 11 × 3 = 33 bits with a 3-bit fixed code and 88 bits in ASCII. The message encodes as
01101110100010101101110.
This is the calculator’s starting example. Press play to watch the four merges.
Measuring the result
If symbol has frequency and its code has bits, the encoded message has bits, and the average code length is that total divided by . Shannon’s source coding theorem gives a lower bound: no prefix code can average fewer bits per symbol than the entropy
A Huffman code always satisfies . It equals the entropy exactly when every probability is a power of ½, as in the “Probabilities” example with weights 0.5, 0.25, 0.25. The calculator prints the average and the entropy side by side.
The classic textbook table (a 45, b 13, c 12, d 16, e 9, f 5, per 100 characters) needs 300 bits with a 3-bit fixed code and 224 with Huffman coding, a saving of about 25%.
Why the greedy choice is optimal
Two facts make the proof work, and together they show by induction on the number of symbols that Huffman’s code is optimal:
- The two rarest symbols can be siblings at the deepest level. In any optimal tree, swapping a rare symbol into the deepest leaf never increases the total, because the rarer symbol then pays for the longer code.
- Merging them reduces the problem. Replace the two rarest symbols by one symbol of weight . An optimal tree for the smaller problem, with that leaf split back into and , is optimal for the original, because the split adds exactly to the cost whichever tree you start from.
Where Huffman coding is used
Huffman codes are the final stage of DEFLATE (used by ZIP, gzip and PNG), of baseline JPEG, and of MP3 audio. In practice they are combined with other steps: DEFLATE first replaces repeated strings with back-references (LZ77) and then Huffman-codes what remains, and JPEG Huffman-codes quantised frequency coefficients. Huffman coding only exploits how often each symbol appears, not patterns such as “q is followed by u”, which is why it is rarely used alone.
Two practical details: the decoder needs the code as well as the bits, so files store the code lengths (a “canonical” Huffman code can be rebuilt from lengths alone); and because every code is a whole number of bits, a symbol with probability 0.99 still costs at least 1 bit. Arithmetic coding and asymmetric numeral systems get closer to the entropy in that case.
Using the calculator
- Text to encode counts every character, including spaces (shown as ␣) and capitals, and shows the encoded bit string.
- Frequency table takes
symbol:weightpairs separated by commas or new lines. Weights can be counts or probabilities. - Step through the merges with the player controls or the arrow keys. The queue panel shows the trees waiting to be merged, lightest first.
- The address bar updates as you go, so you can share a link to your example.
Prefix codes and binary trees connect to other pages here: a prefix code is decoded by a small finite-state machine, and the codes are a form of the binary strings counted on the power set calculator page.
References
- D. A. Huffman, “A method for the construction of minimum-redundancy codes”, Proceedings of the IRE 40(9), 1952, 1098–1101.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022. Section 15.3, Huffman codes.
- T. M. Cover and J. A. Thomas, Elements of Information Theory, 2nd ed., Wiley, 2006. Chapter 5, data compression.
- K. Sayood, Introduction to Data Compression, 5th ed., Morgan Kaufmann, 2017. Chapter 3.