Huffman Coding and Prefix Codes
Repeatedly merge the two lightest nodes, then read each symbol’s code from its root-to-leaf path.
Core Intuition & How It Works
Huffman coding builds an optimal prefix-free binary code by repeatedly merging the two lowest-frequency symbols using a min-heap. Frequent symbols receive shorter bit codes, minimizing average encoded length.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n log n) |
| Space Complexity | O(n) |
| Topic Chapter | Chapter 10: Greedy Algorithms |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Ensure every encoded symbol sits at a leaf node so no code is ever a prefix of another, enabling unambiguous streaming decoding.
Common Pitfalls & Edge Cases
Forgetting the single-symbol edge case (assigning code "0" instead of an empty string) or using a max-heap by mistake.
Real-World & Technical Interview Applications
DEFLATE / gzip / PNG compression, JPEG entropy coding, and lossless data transmission.