Huffman Coding Calculator

Frequencies in, tree and codebook out — with every merge shown, the tie-break rule stated, and the other equally optimal codes named rather than hidden.

Source

The text below is counted symbol by symbol. A character outside the basic plane counts as one symbol, not two.

Spaces and newlines are symbols like any other. Counting them changes every number on this page, so the choice is a control rather than a default.

Decode a bitstream

Left empty this shows the round trip of the source text above.

  • symbols: 4
  • total: 11
  • encoded: 21 bits
  • average length: 1.9091 bits/symbol
Note:

Which tree you get depends on how ties are broken, and this page uses one specific rule

Huffman’s algorithm is optimal but not unique. With n leaves there are n − 1 internal nodes, each with two possible orientations, so at least 2^(n−1) arrangements of a Huffman tree exist for the same weights — all of them with the same cost. If your textbook shows different bit patterns for the same weights, check the lengths: they are probably the same, and both codes are then equally correct.

Moffat (2019) §2.2: symbols are numbered 0…m−1 in ascending code-point order, and the heap is keyed on the tuple (weight, isInternal ? 1 : 0, tieRank) with tieRank = −symbolIndex for leaves and the creation sequence number for internal nodes. So: on a tie between leaves the higher-numbered symbol is preferred; on a tie between a leaf and an internal node the leaf is preferred; on a tie between internal nodes the one formed earlier is preferred. The first node popped becomes the 0 (left) child.

Array.prototype.sort has been stable since ES2019, but a binary heap is not. The tuple key is mandatory, not an optimisation — without it the same input gives different codes on different runs.

Merge log

Each step removes the two lightest nodes and inserts their parent. The node popped first becomes the 0 child, the node popped second becomes the 1 child.
StepPopped first — becomes the 0 childPopped second — becomes the 1 childNew nodeTie broken?
1M w 1, leaf, key (1, 0, −1)P w 2, leaf, key (2, 0, −2)N0 = 3no
2N0 w 3, internal, key (3, 1, 0)S w 4, leaf, key (4, 0, −3)N1 = 7the rule decided this step
3I w 4, leaf, key (4, 0, 0)N1 w 7, internal, key (7, 1, 1)N2 = 11no

1 of these steps was decided by the tie-break rule rather than by the weights, so other trees of exactly the same cost exist. The cost — 21 bits — is the part that is unique.

Codebook

The codebook read off the tree: 0 for a left edge, 1 for a right edge, root to leaf. The last column sums to the total encoded size.
SymbolFrequency fProbability pCodeLength ℓf × ℓ
I40.363636014
M10.09090910033
P20.18181810136
S40.3636361128
total11121 bits

Canonical re-assignment

Sorted by (length, symbol) — the order RFC 1951’s construction walks, so the sort is part of the working. All codes of a given length are lexicographically consecutive, and shorter codes precede longer ones.
SymbolLength ℓTree codeCanonical code
I100
S21110
M3100110
P3101111

The codes change; the lengths — and therefore the total size — do not.

Kraft sum

Σ 2^(−ℓ) = 2^(−1) + 2^(−3) + 2^(−3) + 2^(−2) = 1

A Kraft sum of exactly 1 means the code is prefix-free and complete: no codeword is a prefix of another, and no bit pattern is wasted.

What it costs

  • fixed-length: 2 bits × 11 symbols = 22 bits
  • Huffman: Σ f·ℓ = 21 bits
  • entropy floor: 11 × H = 20.0537 bits — no code can go below this
  • space savings against fixed-length: 4.55%

Encoded (tree codes)

100011110111101011010

21 bits

Encoded (canonical codes)

110010100101001111110

21 bits — the same length, different bits

Decoded

MISSISSIPPI

every bit was consumed by a complete codeword

Huffman code over 4 symbols

4 symbols, 11 total occurrences. Repeatedly merge the two lightest nodes until one remains.

Each step removes the two lightest nodes and inserts their parent. — Huffman code over 4 symbols
Step0 child (popped first)1 child (popped second)New nodeTie broken?
1"M" (1)"P" (2)N0 = 3no
2N0 (3)"S" (4)N1 = 7yes
3"I" (4)N1 (7)N2 = 11no
The canonical column has the same lengths, so the total cost is identical. — Huffman code over 4 symbols
SymbolFrequencyProbabilityCodeLengthfreq × lengthCanonical
I40.3636360140
M10.09090910033110
P20.18181810136111
S40.363636112810

Total encoded size21 bitsΣ frequency × code length, which also equals the sum of every internal node weight

Average code length1.909091 bits/symbol

Longest codeword3 bits

Kraft sum Σ 2^(−ℓ)1.000000exactly 1, so the code is complete

Moffat (2019) §2.2: symbols are numbered 0…m−1 in ascending code-point order, and the heap is keyed on the tuple (weight, isInternal ? 1 : 0, tieRank) with tieRank = −symbolIndex for leaves and the creation sequence number for internal nodes. So: on a tie between leaves the higher-numbered symbol is preferred; on a tie between a leaf and an internal node the leaf is preferred; on a tie between internal nodes the one formed earlier is preferred. The first node popped becomes the 0 (left) child.

Warning:

1 of the 3 merges had to break a weight tie, so this is ONE of several equally optimal codes — a textbook that breaks ties differently will show different bit patterns for the same total cost. The rule in force is stated above.

Source: D. A. Huffman, Proceedings of the IRE 40(9):1098–1101 (1952); tie-break per A. Moffat, ACM Comput. Surv. 51(4) §2.2 (2019)

The entropy of the same distribution, and the bound it sets

Shannon entropy of 4 symbols

4 symbols, 11 total occurrences. Divide by the total to get probabilities, then take −Σ p·log₂ p.

The surprisal column is the ideal code length; Huffman rounds it to whole bits. — Shannon entropy of 4 symbols
SymbolpSurprisal −log₂ p (bits)Contribution p·(−log₂ p)
I0.3636361.4594320.530702
M0.0909093.4594320.314494
P0.1818182.4594320.447169
S0.3636361.4594320.530702

H1.823068 bits/symbolthe probability-weighted mean of the surprisal column

Total information20.053748 bits11 symbols × H

Maximum possible H2.000000 bits/symbollog₂(4), reached only by the uniform distribution

H / log₂(m)0.911534how close to uniform this source is

Warning:

A symbol of probability 0 contributes exactly 0: the convention 0·log₂0 = 0 is a definition (the limit as p → 0), not an approximation. Evaluating it instead returns NaN, which is the usual bug on this page.

Source: C. E. Shannon, Bell System Technical Journal 27:379–423 (1948), Theorem 2

Note:

Notation used on this page

  • Left edges are 0 and right edges are 1; a codeword is read root to leaf.
  • The node popped first becomes the left (0) child and the node popped second becomes the right (1) child.
  • Symbols are numbered in ascending Unicode code-point order. On a tie between leaves the later symbol is preferred; a leaf beats an internal node; an earlier-formed internal node beats a later one.
  • Weights may be counts or probabilities and are never normalised before the merge — only the reported p column is.
  • ℓ is a codeword length in bits and L = Σ pᵢℓᵢ is the average codeword length.

Start from a worked example

What Huffman coding does

A Huffman code is optimal among prefix codes for a known symbol distribution. It is not the smallest possible encoding of your data, and it is not unique. Both halves of that sentence matter, and the panels above are built around them.

The idea is to stop spending the same number of bits on every symbol. A fixed-width encoding gives MISSISSIPPI the same allowance for the single M as for the four Is; a Huffman code gives the common symbols short codewords and pays for it with longer ones on the rare symbols, which is a win exactly when the distribution is uneven. Here that is 21 bits against 22 for a two-bit fixed code over the same four symbols.

It is the opposite move to a Hamming code, which adds redundancy so that errors can be repaired. A real system compresses first and adds error correction afterwards, in that order, because correcting redundancy you are about to throw away is wasted work.

Prefix codes, and why a bitstream needs no separators

Every symbol sits at a leaf of the tree, so no codeword is a prefix of any other. That is what makes a variable-length code decodable without delimiters: a decoder reads bits one at a time, walks down from the root, and emits a symbol the moment it lands on a leaf — then starts again at the root.

With I = 0, M = 100, P = 101, S = 11, the string MISSISSIPPI encodes to 100011110111101011010. Walk it: 100 reaches M; the next 0 is already a leaf, so I; 11 gives S, and so on to the end, with no separator anywhere and no ambiguity about where one codeword stops.

A code that is notprefix-free can still be decodable, but only with lookahead — and if one codeword is a prefix of another with nothing to distinguish them, the stream is genuinely ambiguous. Huffman’s construction cannot produce that case, because symbols are only ever placed at leaves.

The algorithm, in one sentence

Place every symbol in a priority queue keyed by weight; repeatedly remove the two lightest nodes and insert a new node whose weight is their sum and whose children they are; stop when one node remains. That node is the root.

For MISSISSIPPI the counts are I 4, M 1, P 2, S 4, and three merges finish the tree: M(1) with P(2) makes a node of 3; that node with S(4) makes 7; I(4) with 7 makes the root at 11. Every merge is listed above with the weights it saw, so the sequence can be checked step by step rather than taken on trust.

The reason it is optimal is an exchange argument: in some optimal tree the two least frequent symbols are siblings at the deepest level, so merging them first loses nothing, and the same argument applies to the smaller problem that remains. The total cost is the sum of every internal node’s weight, which is why the merge order and the cost are the same fact seen twice.

Ties, and the rule this page uses

When two nodes weigh the same, the algorithm has a genuine choice, and different choices give different trees with identical cost. That is the single most common reason a student decides a Huffman tool is broken. So the rule is stated rather than left implicit:

Moffat (2019) §2.2: symbols are numbered 0…m−1 in ascending code-point order, and the heap is keyed on the tuple (weight, isInternal ? 1 : 0, tieRank) with tieRank = −symbolIndex for leaves and the creation sequence number for internal nodes. So: on a tie between leaves the higher-numbered symbol is preferred; on a tie between a leaf and an internal node the leaf is preferred; on a tie between internal nodes the one formed earlier is preferred. The first node popped becomes the 0 (left) child.

Of the 3 merges on MISSISSIPPI, the merge log above marks 1 step as decided by this rule rather than by the weights: I and S both weigh 4 at that point, and the leaf-order clause settles it. If your textbook shows different bit patterns for the same weights, compare the lengths before assuming one of you is wrong — they are probably identical, and both codes are then equally correct.

Array.prototype.sort has been stable since ES2019, but a binary heap is not. The tuple key is mandatory, not an optimisation — without it the same input gives different codes on different runs. That is why the key carries the creation sequence number and the symbol index, and not merely the weight.

Reading the codes off the tree

Walk from the root to a leaf and write 0 for every step to the left child and 1for every step to the right; the string you have written is that symbol’s codeword, and its length is the leaf’s depth. The choice of which child is 0 is a convention, not a result: swapping the two children of any node flips one bit in every codeword below it and changes nothing about the cost.

With n leaves the tree has n − 1 internal nodes, each of which can be flipped independently, so at least 2^(n−1) distinct labellings of the same shape exist. All of them are correct Huffman codes.

The Kraft sum

For any binary prefix code the codeword lengths satisfy Σ 2^(−ℓᵢ) ≤ 1, and a set of lengths satisfying that inequality can always be realised as a prefix code. It is a statement about the lengths alone; the bit patterns never enter it.

A sum of exactly 1 means the code is complete: every leaf of the binary tree is used and no bit pattern is wasted. A sum below 1 means the code is prefix-free but incomplete — some of the code space is unreachable, which happens for a one-symbol alphabet, where this page emits the one-bit codeword 0 and the sum is 1/2. A sum above 1 is impossible for a prefix code; if you compute one, the lengths you have are not the lengths of any prefix code.

Canonical Huffman codes

Once the lengths are known the bit patterns can be assigned by a rule instead of by the tree. RFC 1951 §3.2.2 states it in two clauses: “All codes of a given bit length have lexicographically consecutive values, in the same order as the symbols they represent” and “Shorter codes lexicographically precede longer codes.” Sort by length and then by symbol, start at 0, add 1 per codeword and shift left by one whenever the length increases.

For MISSISSIPPI the tree gives I = 0, M = 100, P = 101, S = 11 and the canonical rule gives I = 0, S = 10, M = 110, P = 111. Both encode the message in 21 bits — 100011110111101011010 against 110010100101001111110. The codes change; the lengths — and therefore the total size — do not.

The payoff is that a decoder no longer needs the tree. Send the code lengthsand the canonical rule rebuilds the identical codebook, which is why every deployed format below transmits lengths. Run the RFC’s own printed example through this page’s implementation — lengths A 3, B 3, C 3, D 3, E 3, F 2, G 4, H 4 — and it reproduces the RFC’s answer exactly: F = 00, A = 010, B = 011, C = 100, D = 101, E = 110, G = 1110, H = 1111.

Several optimal codes exist

Every optimal code for these weights costs exactly 21 bits. That is the part that is unique, and it is the only part this page claims. The tree, the bit patterns, and in some cases even the individual lengths are not.

For MISSISSIPPI the divergence is easy to name. This page produces I = 0, M = 100, P = 101, S = 11; many textbooks and most online tools produce the mirror assignment with S = 0 and I = 10, because they broke the weight-4 tie the other way. Both cost 21 bits and both are correct Huffman codes.

Sometimes the disagreement is deeper than the bit patterns: two distributions shipped as worked examples reach different length multisetsat equal cost. Moffat’s rule has the useful side effect of minimising the longest codeword, which is the choice this page makes and the better one to teach, because a shorter maximum length is what a table-driven decoder actually cares about.

Equal cost, different lengths
DistributionLength multisetCostLongest codewordWhich one
ABRACADABRA (A 5, B 2, C 1, D 1, R 2)1, 3, 3, 3, 323 bits3this page’s tree
ABRACADABRA, the other reachable shape1, 2, 3, 4, 423 bits4equally correct, one bit deeper
Weights 10, 6, 2, 1, 1, 1 (Moffat)1, 2, 4, 4, 4, 442 bits4this page’s tree
Weights 10, 6, 2, 1, 1, 1, the other reachable shape1, 2, 3, 4, 5, 542 bits5equally correct, one bit deeper

A minimum-redundancy code Huffman cannot produce

Take the weights 8, 7, 6, 5, 4, 3. Huffman merges 3 + 4 = 7, then 5 + 6 = 11, then 7 + 7 = 14, then 8 + 11 = 19, then 14 + 19 = 33, for a cost of 84 bits and the length vector (2, 2, 3, 3, 3, 3). The canonical re-assignment of those lengths is 00, 01, 100, 101, 110, 111, and it costs the same 84 bits.

But the treethat assignment describes places the two heaviest symbols, 8 and 7, under a shared parent of weight 15 — and Huffman never forms that node, because it always merges the two lightest first and 3 + 4 = 7 comes long before any pair involving 8. So the canonical code here is a minimum-redundancy code that Huffman’s algorithm cannot construct, even though its lengths are ones Huffman does reach. “Minimum-redundancy code” is a strictly larger set than “Huffman code”.

How good is it?

Three numbers answer that, and all three are above. A fixed-length code over m symbols spends ⌈log₂ m⌉ bits each; the Huffman code spends Σ f·ℓ; and no code of any kind can go below the entropy floor N × H. For MISSISSIPPI that is 22 bits fixed, 21 bits Huffman, and a floor of 1.8231 bits per symbol — so the code is within about a tenth of a bit per symbol of the theoretical minimum, and the entropy floor explains why that gap cannot be closed by a better tree.

The gap can be much worse. With weights 96, 1, 1, 1, 1 the entropy is 0.3223 bits per symbol but the Huffman code averages 1.08 — 235% above the floor, and nothing is wrong with the code. A prefix code cannot spend less than one whole bit on a symbol, and this source wants to spend about 0.06 bits on its dominant symbol. Arithmetic coding and range coding do spend fractional bits, at the cost of no longer being a table lookup. The loss is worst exactly when one symbol dominates, which is where a naive reading of “Huffman is optimal” misleads.

The other end is just as instructive: over a uniform alphabet Huffman gives every symbol the same length and saves nothing, and the entropy of that distribution is exactly log₂ m, which says the same thing in one number.

Where Huffman coding is used

All three of the formats below transmit canonical codes, for the reason in the section above: lengths are enough to rebuild the codebook, and lengths are far cheaper to send than a tree.

Huffman coding in deployed formats
FormatWhere the code sits
DEFLATE — gzip, PNG, ZIPTwo canonical Huffman codes per block, one for literals and match lengths and one for distances, with the lengths themselves Huffman-coded.
JPEGThe entropy stage after the discrete cosine transform and quantisation; the tables are transmitted as code lengths and counts.
MP3The quantised frequency lines are split into regions, each coded with one of a fixed set of built-in Huffman tables.

Notation used on this page

  • Left edges are 0 and right edges are 1; a codeword is read from the root to the leaf.
  • The node popped first becomes the left (0) child; the node popped second becomes the right (1) child.
  • Symbols are numbered in ascending Unicode code-point order, and the tie-break above is stated in terms of that numbering.
  • Weights may be counts or probabilities and are never normalised before the merge. Only the reported p column is normalised.
  • A one-symbol alphabet is given the one-bit code 0, so its Kraft sum is 1/2 rather than 1.
  • ℓ is a codeword length in bits and L = Σ pᵢℓᵢ is the average codeword length; H is the Shannon entropy of the same distribution, in bits per symbol.
  • Whitespace is counted as a symbol unless the switch above is turned off, because that choice changes every number on the page.

Sources

Worked examples