Loading algorithms…

Loading visualizer…

Algorithms/Tree/Huffman Coding

Huffman Coding

Build an optimal prefix-free code by repeatedly merging the two least-frequent nodes. Watch the greedy tree take shape and the codes fall out.

GreedyPrefix CodeCompression
Step 1 of 12: Counted 11 characters → 5 distinct symbols. Each becomes a leaf weighted by its frequency.
1 / 12
Speed

Counted 11 characters → 5 distinct symbols. Each becomes a leaf weighted by its frequency.

Frequencies

A:5B:2R:2C:1D:1

Code table

Codes appear once the tree is complete.

huffman.js
1function huffman(text) {
2 const freq = countFrequencies(text);
3 const pq = [...leaves].sort(by freq);
4 
5 while (pq.length > 1) {
6 const a = pq.shift(); // lightest
7 const b = pq.shift(); // 2nd lightest
8 pq.push(merge(a, b));
9 pq.sort(by freq);
10 }
11 
12 const root = pq[0];
13 return assignCodes(root, '');
14}

Type A–Z text or pick a preset · Amber ring = pair being merged · Codes appear once the tree completes

About the Huffman Coding algorithm

Build an optimal prefix-free code by repeatedly merging the two least-frequent nodes. Watch the greedy tree take shape and the codes fall out.

Category
Tree
Difficulty
Medium
Time complexity
O(n log n)
Space complexity
O(n)
Introduced
1952
←Previous Algorithm
AVL Tree
TreeO(log n)
Next Algorithm→
Union-Find (DSU)
O(α(n)) amortizedData Structures