DSA Notes
Build Huffman codes from scratch — understand frequency-based prefix codes, priority queue construction, tree building, encoding/decoding, and compression analysis.
What is Huffman Coding?
Huffman coding is a greedy algorithm that produces optimal prefix-free variable-length codes for data compression. Characters that appear frequently get shorter bit sequences, while rare characters get longer ones. The result: the encoded message uses fewer total bits than a fixed-length encoding.
The Core Idea
In ASCII, every character takes 8 bits regardless of frequency. But if 'e' appears 1000 times and 'z' appears once, giving 'e' a 2-bit code and 'z' a 10-bit code saves enormous space. The challenge: how do you assign codes so that no code is a prefix of another (ensuring unambiguous decoding)?
Huffman's insight: build a binary tree bottom-up, repeatedly merging the two least-frequent nodes. The path from root to leaf gives each character's code (left = 0, right = 1).
Algorithm Steps
- Count the frequency of each character in the input.
- Create a leaf node for each character and insert into a min-priority queue (keyed by frequency).
- While the queue has more than one node:
a. Extract the two nodes with lowest frequency (call them left and right). b. Create a new internal node with frequency = left.freq + right.freq. c. Set left and right as children of this new node. d. Insert the new node back into the priority queue.
- The last remaining node is the root of the Huffman tree.
- Traverse the tree to assign codes: going left adds '0', going right adds '1'.
Dry Run Example
| Input | "ABRACADABRA" |
| Frequencies | A=5, B=2, R=2, C=1, D=1 |
| Step 1 | Priority queue: [C:1, D:1, B:2, R:2, A:5] |
| Step 2: Merge C(1) + D(1) | CD(2) |
| Queue | [B:2, R:2, CD:2, A:5] |
| Step 3: Merge B(2) + R(2) | BR(4) |
| Queue | [CD:2, A:5, BR:4] |
| Step 4: Merge CD(2) + BR(4) | CDBR(6) |
| Wait — min is CD | 2 and A:5? No, re-sort: [CD:2, BR:4, A:5] |
| Merge CD(2) + BR(4) | CDBR(6) |
| Queue | [A:5, CDBR:6] |
| Step 5: Merge A(5) + CDBR(6) | Root(11) |
| Codes | A=0, C=100, D=101, B=110, R=111 |
| Compression ratio | 23/33 = 69.7% (saved 30.3%) |
Python Implementation
C++ Implementation
Why Huffman Codes Are Optimal
Huffman produces the optimal prefix code (minimum expected bit length) for a given frequency distribution. The greedy choice: always merging the two least frequent nodes ensures that rare characters end up deepest in the tree (longest codes) and frequent characters stay near the root (shortest codes).
Proof sketch: If we swapped a deep frequent character with a shallow rare one, total bits would increase (more occurrences × longer code > fewer occurrences × longer code).
Complexity Analysis
| Operation | Time | Notes |
|---|---|---|
| Frequency counting | O(n) | n = input length |
| Building heap | O(k log k) | k = unique characters |
| Tree construction | O(k log k) | k-1 merges, each O(log k) |
| Code generation | O(k) | Tree traversal |
| Encoding | O(n) | One lookup per character |
| Decoding | O(m) | m = encoded bit length |
| Total | O(n + k log k) |
Compression Ratio
The theoretical compression ratio depends on entropy H:
Huffman is within 1 bit of the entropy lower bound per character.
Real-World Applications
- ZIP/GZIP compression: Uses Huffman as part of the DEFLATE algorithm
- JPEG images: Huffman coding for quantized DCT coefficients
- MP3 audio: Huffman tables for encoded frequency data
- Fax machines (Group 3): Modified Huffman for run-length encoded data
- HTTP/2: HPACK header compression uses Huffman-coded strings
Key Takeaways
Huffman coding is a beautiful example of greedy optimality. The min-heap merge strategy guarantees optimal prefix codes. The algorithm runs in O(n + k log k) time and achieves compression within 1 bit/symbol of the theoretical entropy limit. It remains the foundation of modern lossless compression despite being invented in 1952.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Huffman Coding — Data Structures & Algorithms.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, greedy, huffman, coding
Related Data Structures & Algorithms Topics