Huffman Coding Calculator
Builds the optimal prefix-free binary code for a set of symbol frequencies: the code that minimizes the total number of bits needed to encode a message with those exact frequencies, subject to no codeword being a prefix of another.
How the tree is built
Repeatedly take the two least-frequent nodes — starting with the individual symbols — and merge them into a new node whose frequency is their sum, until one node remains. Every merge assigns a 0 to one branch and a 1 to the other, and a symbol's final code is the sequence of branches from the root to its leaf.
The greedy choice — always merging the two smallest — is what makes the result optimal, not just a valid prefix code: it guarantees the least-frequent symbols end up deepest in the tree with the longest codes, and the most frequent symbols stay shallow with the shortest ones. That single property (proved by an exchange argument) is why Huffman coding needs no backtracking to find the true optimum.
Why prefix-free matters
A prefix-free code means no complete codeword is the start of another — 0 and 01 could never both appear. Without that property, a decoder reading a bitstream would not know where one codeword ends and the next begins. Huffman's algorithm produces prefix-free codes automatically, because every codeword corresponds to a leaf of the tree, and a leaf can never be an ancestor of another leaf.
When ties matter, and when they don't
Coursework often gives frequencies with ties, and different textbooks break them differently, which can produce a different-looking tree from the same input. This does not mean one answer is wrong: whenever two trees are both genuinely optimal, they encode the same message in the same total number of bits, even though individual codewords and lengths can differ. If you are checking homework and the codes don't match, compare the total bits first — that number is what "optimal" actually guarantees.
What Huffman coding does not do
It assumes frequencies are known in advance and fixed for the whole message — real compressors like DEFLATE and Brotli instead adapt as they go, and modern formats increasingly use arithmetic or range coding, which can beat Huffman when a symbol's true probability isn't a clean power of two. Huffman coding is also not the layer that finds repeated substrings (that's what LZ77-style dictionary matching does); it compresses whatever symbol stream it is given.