Huffman Coding
Compresses data by giving frequent characters short bit codes and rare ones long codes. A greedy strategy that repeatedly merges the two lowest-frequency nodes into a tree produces an optimal prefix code.
01Huffman Coding
Explore How It WorksStart Huffman coding. Frequencies a:5, b:2, c:1, d:1. Repeatedly merge the two smallest into a tree.
Merge the two smallest, c(1) and d(1), into a parent(2).
Next merge b(2) with the node(2) just built into a parent(4).
Finally merge a(5) with the node(4) into the root(9). Tree complete.
Reading left=0, right=1 gives a=0, b=10, c=110, d=111. The frequent a gets the shortest code, shrinking the total length.
02 Understand It Simply
For EveryoneFrequent characters get short codes and rare ones get long codes. No code is a prefix of another, so the stream decodes without separators.
Repeatedly merges the two lowest-frequency items into a tree and assigns short bit codes to frequent characters.
The result minimizes total data length.
- –File compression (ZIP
- –JPEG)
- –data-transfer encoding
03 Python Implementation
A clean, readable reference implementation of the core logic of Huffman Coding.
04 Frequently Asked Questions
FAQWhat is Huffman Coding?+
Compresses data by giving frequent characters short bit codes and rare ones long codes. A greedy strategy that repeatedly merges the two lowest-frequency nodes into a tree produces an optimal prefix code.
What is the time complexity of Huffman Coding?+
The time complexity of Huffman Coding is O(n log n). Follow the step-by-step visualization to see exactly why.
Where is Huffman Coding used?+
File compression (ZIP, JPEG), data-transfer encoding.
What's a simple analogy for Huffman Coding?+
Frequent characters get short codes and rare ones get long codes. No code is a prefix of another, so the stream decodes without separators.
