Data Structures and Algorithms • C# examples
Huffman Coding and Prefix-Free Codes
Build an optimal variable-length prefix code for known symbol frequencies.
Concept
Huffman coding repeatedly combines the two least frequent trees. A min-priority queue implements this process, producing a prefix-free code in which no symbol code is a prefix of another. The result minimizes weighted code length among binary prefix codes for the supplied frequencies.
How to approach it
Insert each symbol as a leaf, combine two minimum-frequency nodes, and traverse the final tree to assign bits.
Complexity
O(k log k) for k distinct symbols with a binary heap.
C# example
while (queue.Count > 1)
{
var left = queue.Dequeue();
var right = queue.Dequeue();
queue.Enqueue(new Node(left.Weight + right.Weight, left, right));
}
Expected result or behavior
The final tree assigns shorter paths to more frequent symbols.
Practice exercise
For a frequency table, compute each symbol’s code length and the total weighted length.
Key takeaway: Huffman’s greedy combination is justified by an optimal-prefix-code argument.