Huffman Coding Explained: Greedy Construction, Prefix Codes and a Worked Example
Build a Huffman tree step by step, derive exact prefix codes, verify the 224-bit weighted cost twice, and learn why the greedy merge is optimal.
KnowledgeGate Team
Exam prep & CS education

Joining the two smallest frequencies is easy to memorise but harder to justify, trace, and translate into an encoded length without losing a branch. Huffman coding becomes easier when each merge has a reason and every cost has a cross-check. For frequencies 5, 9, 12, 13, 16, and 45, the resulting prefix code costs 224 bits; the weighted-path calculation and merge-cost sum independently reach that total.
Greedy algorithm basics: local choices and a global optimum
A greedy algorithm builds a solution through feasible, irrevocable choices using the best local criterion at each step. Its candidate set holds available choices. A feasibility test enforces constraints, a selection rule picks the locally preferred candidate, and the objective value measures what the complete solution minimises or maximises.
Choosing a minimum or maximum does not prove correctness. The greedy-choice property says some optimal solution can begin with the proposed choice. Optimal substructure says that, once it is fixed, solving the smaller remaining instance optimally completes an optimal whole. The broader Greedy Algorithms: Strategy and Problems guide applies these ideas to other problem shapes.
The same two-minimum tree solves Optimal Merge Pattern by minimising repeated file-processing cost. In Huffman coding, that tree instead determines prefix-code lengths, literal bit paths, and unambiguous decoding.
Huffman coding: frequencies, prefix-free codes and the min-heap rule
Huffman coding is a lossless, variable-length prefix-coding method. More frequent symbols should end nearer the root with shorter codewords, while less frequent symbols can sit deeper. Prefix-free means no complete codeword is a prefix of another. A decoder can therefore read the bitstream left to right without separators.
For the binary algorithm, create one leaf for each symbol and its positive frequency or weight. Put every leaf in a min-priority queue. Remove the two minimum-weight nodes, make them children of a new node whose weight is their sum, and reinsert the parent. Repeat until only one root remains. Label each left edge 0 and each right edge 1. A root-to-leaf path gives that leaf's code.
Edge swaps or equal-frequency tie choices may change literal bit patterns without changing prefix-freeness or optimal cost. Alphabetic order is not the selection rule.
Huffman construction worked example: six frequencies, one tree
Use a 100-symbol block with A=5, B=9, C=12, D=13, E=16 and F=45. The frequencies sum to 5+9+12+13+16+45=100. The initial ordered queue is [A5, B9, C12, D13, E16, F45].
Perform all five merges:
Remove
A5andB9. CreateN14. The queue becomes[C12, D13, N14, E16, F45].Remove
C12andD13. CreateN25. The queue becomes[N14, E16, N25, F45].Remove
N14andE16. CreateN30. The queue becomes[N25, N30, F45].Remove
N25andN30. CreateN55. The queue becomes[F45, N55].Remove
F45andN55. Create rootN100. The queue is[N100].
After every step, the queue contains roots of disjoint partial prefix trees. Each parent weight equals the sum of all leaf frequencies below it. That invariant explains both why the final root is 100 and why the new node must re-enter the global minimum queue. Sorting once and then pairing adjacent original items would fail at step two, because N14 must compete with the unmerged weights.

Huffman codes and encoded length: derive and cross-check
Fix the smaller-weight child on the left where applicable, label left 0 and right 1. Root N100 has F45 on the left and N55 on the right. N55 contains left child N25 and right child N30. N25 contains C12 and D13; N30 contains N14 and E16; N14 contains A5 and B9.
Symbol | Code | Length | Frequency x length |
|---|---|---|---|
F |
| 1 |
|
C |
| 3 |
|
D |
| 3 |
|
A |
| 4 |
|
B |
| 4 |
|
E |
| 3 |
|
The weighted path length is 45+36+39+20+36+48=224 bits for the block, so the average is 224/100=2.24 bits per symbol. Independently, sum the internal merge weights: 14+25+30+55+100=224. The totals match because every merge moves each leaf below the new parent one level deeper and adds those frequencies once to the eventual cost.
Six fixed-length symbols require ceil(log2 6)=3 bits each. The same payload then needs 100x3=300 bits. Huffman saves 300-224=76 payload bits, or 76/300 x 100=25.33%. This comparison excludes storage or transmission of the tree and codebook.
To encode FACE, concatenate F|A|C|E: 0|1100|100|111 = 01100100111, an 11-bit string. Decode at leaf boundaries: 0 -> F, 1100 -> A, 100 -> C, 111 -> E. No delimiter is required.

Why Huffman's greedy choice is optimal
In a full binary prefix tree, two deepest leaves are siblings. Suppose heavier symbols occupy deepest positions while lighter symbols sit higher. Exchanging the lighter weights into the deeper positions cannot increase the weighted path length, which is the sum of each frequency multiplied by its depth. Therefore, some optimal tree places the two minimum frequencies at maximum depth as siblings.
For our first choice, A=5 and B=9 may be siblings. Contract them into pseudo-symbol N14. Build an optimal prefix tree for [C12, D13, N14, E16, F45], then expand N14 back into children A5 and B9. Expansion moves both leaves one level deeper, adding exactly 5+9=14 to the cost.
Repeating this contraction establishes optimal substructure and produces the complete merge sequence. The proof establishes optimality among binary prefix codes for the supplied weights. It does not make every locally smallest-looking choice safe in every optimisation problem.
Huffman algorithm complexity and exam-safe shortcuts
For n distinct symbols, binary min-heap construction takes O(n). Huffman performs n-1 merges. Each uses two extract-min operations and one insertion, each costing O(log n), so construction takes O(n log n) time and O(n) space. If frequencies arrive sorted, an advanced two-queue method can construct the tree in linear time.
The standard heap shape is:
heap = entries (weight, stable_tie_id, node)
while heap size > 1:
left = extract_min(heap)
right = extract_min(heap)
parent = node(left.weight + right.weight, left, right)
insert(heap, parent)
DFS(root, path) records path at every leafThe stable tie identifier makes equal weights deterministic. For a refresher on the notation, see Time Complexity and Asymptotic Notation: Big-O. If only the total weighted code length is required, sum internal merge weights. Here, 14+25+30+55+100=224, so bit labels are unnecessary unless actual codes or decoding are requested.
Huffman coding traps and defensible question shapes
Trap | What goes wrong | Repair |
|---|---|---|
Use a max-heap | Heavy symbols get long codes | Extract two minima |
Pair the original list | New sums never compete | Reinsert each parent |
Let one code prefix another | Decoding is ambiguous | Use root-to-leaf codes |
Demand one code table | Valid alternatives look wrong | Check cost and prefix-freeness |
Add code lengths only | Frequencies disappear | Sum frequency x length |
Call 224 the file size | Codebook overhead is omitted | Say payload cost |
Use an empty code for one symbol | No bit is sent | Usually assign |
Question shapes include selecting the next merge, completing a partial tree, identifying a prefix-free set, calculating weighted or average length, deriving heap complexity, and judging ties or optimality. For practice, trace one merge table by hand, then derive its codes and weighted cost before checking the result. The GATE CS Exam Preparation category provides the wider subject route.
Huffman coding in the short version and the next step
Keep this five-step chain: put every weight in a min-heap, merge the two smallest, reinsert their sum, repeat until one root remains, then read root-to-leaf edge labels. Check every reinserted sum. In our example, the merge-cost sum is 224, the average is 2.24 bits per symbol, and the fixed-length payload is 300 bits. For a structured route through broader Algorithms preparation, GATE Guidance by Sanchit Sir is an optional next step.
Keep learning
Greedy Algorithms and Huffman Coding MCQs: 12 Solved Questions with Explanations
Test greedy algorithm fundamentals and Huffman coding through 12 solved MCQs, including tree construction, weighted code length, decoding, and complexity.
Infix, Postfix and Prefix Expressions: Stack Rules, Conversions and Worked Examples
Learn how one expression becomes infix, postfix and prefix form. Follow the operator stack, build the expression tree and evaluate both stack notations safely.
Infix, Postfix and Prefix MCQs: 12 Solved Questions with Step-by-Step Explanations
Solve 12 expression-notation MCQs in increasing difficulty, from basic stack use to conversions, associativity and maximum operand-stack depth.
Left Factoring in Compiler Design: Prefix Rules, Worked Grammars and Exam Traps
Learn how to find a useful common prefix, factor a grammar to a fixed point, preserve empty suffixes, and test what the result does and does not prove.





