What is Huffman Coding?
Huffman Coding is a greedy algorithm used for lossless data compression. It assigns shorter binary codes to more frequent characters and longer codes to rarer ones, guaranteeing no code is a prefix of another so the encoded stream can be decoded unambiguously.
The algorithm repeatedly makes the locally optimal choice - always merging the two least-frequent nodes in the priority queue - and this greedy strategy provably produces a globally optimal prefix code, unlike Dijkstra's Algorithm which is greedy over graph distances instead of frequencies.
Time & Space Complexity
- Build Frequency TableO(n)
- Build Huffman TreeO(k log k)
- Encode InputO(n)
- SpaceO(k)
* n = length of the input text, k = number of distinct characters.
Real-World Use Cases
- ✓File CompressionUsed as a component in ZIP, GZIP, and PNG compression formats.
- ✓JPEG ImagesApplied after quantization to compress image data further.
- ✓MP3 & Video CodecsEntropy coding stage in many multimedia compression pipelines.