Algorithms · Visualized
Compression: Huffman
Compression & Encoding
Shrink data with runs, frequencies, and clever codes.
A compression technique that assigns shorter binary codes to more frequent characters and longer codes to rarer ones, minimizing the total encoded size. Time: O(n log n) average, O(n log n), where n is the number of distinct characters worst; space: O(n) — the Huffman tree and code table.
Big-O: Huffman gives prefix-free optimal codes.
Huffman Coding
Compression / EncodingA compression technique that assigns shorter binary codes to more frequent characters and longer codes to rarer ones, minimizing the total encoded size. It builds an optimal 'prefix code' tree by repeatedly combining the two least-frequent nodes into a new parent node, using a min-heap, until only one tree remains.
How Huffman Works
- Count the frequency of every character in the input.
- Create a leaf node for each character with its frequency, and add all leaves to a min-heap (priority queue) ordered by frequency.
- Repeatedly remove the two nodes with the smallest frequencies from the heap, create a new internal node with these two as children and a frequency equal to their sum, and insert this new node back into the heap.
- Continue merging until only one node remains in the heap — this is the root of the Huffman tree.
- Assign codes by traversing the tree from the root: each left branch adds a '0' and each right branch adds a '1' to the code, and each leaf's accumulated path is that character's Huffman code.
Huffman Worked Example
Input: {text: aaabbc, frequencies: {a: 3, b: 2, c: 1}}
Min-heap starts with leaves a(3), b(2), c(1). Merge smallest two: c(1)+b(2)=new node(3). Heap now has a(3) and merged-node(3). Merge these: total root(6). Tree: root→left=a (code '0'), root→right=merged-node→left=b(code '10'), right=c(code '11'). Encoded 'aaabbc' becomes '0 0 0 10 10 11' — shorter overall than fixed-length encoding since 'a' (most frequent) gets the shortest code.
| char | freq | code | |
|---|---|---|---|
| a | a | 3 | |
| b | b | 2 | |
| c | c | 1 |
import heapq
from collections import Counter
def huffman_codes(text):
heap = [[freq, char] for char, freq in Counter(text).items()]
heapq.heapify(heap)
while len(heap) > 1:
left = heapq.heappop(heap)
right = heapq.heappop(heap)
heapq.heappush(heap, [left[0] + right[0], left, right])
codes = {}
def walk(node, prefix):
if len(node) == 2:
codes[node[1]] = prefix or '0'
return
walk(node[1], prefix + '0')
walk(node[2], prefix + '1')
if heap:
walk(heap[0], '')
return codesBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Huffman Time & Space Complexity
When to Use Huffman
- Widely used in real compression formats: ZIP, JPEG, MP3, and PDF all use Huffman coding (often combined with other techniques) as part of their compression pipeline.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.