← All animations

๐Ÿ—œ๏ธ Data Compression

A file is just a string of bits โ€” but most files are repetitive and predictable, and that wasted space can be squeezed out. Compression replaces common patterns with short codes and rare ones with longer codes, so the average shrinks. Below: build a Huffman code live, watch run-length encoding win and lose, and meet the hard limit set by entropy.

1. Huffman coding โ€” frequent characters get the shortest codes

Plain text stores every character in a fixed 8 bits. Huffman counts how often each character appears, then builds a tree by repeatedly merging the two least-frequent nodes. Reading the tree (left = 0, right = 1) gives a prefix-free code: common letters end up near the root with short codes, rare ones sit deep with long codes. Type below and watch it rebuild.

Original: 0 bits Huffman: 0 bits Saved 0% Entropy โ‰ˆ 0.00 bits/char

2. Run-length encoding โ€” and why you can't compress everything

The simplest scheme of all: replace a run of identical symbols with a count + symbol. AAAABBB becomes 4A3B. On repetitive data it shrinks dramatically. But on random data, runs are length 1, so every symbol becomes two tokens โ€” it gets bigger. No scheme can shrink every possible input (the pigeonhole principle): if some inputs get shorter, others must get longer.

Repetitive: huge savings

3. The big picture โ€” redundancy, entropy, lossless vs lossy

Why does any of this work, and where does it stop?

Compression exploits redundancy & predictability. If the next symbol is easy to guess, it carries little information โ€” and information you can predict, you don't have to store.
Entropy is the limit. Claude Shannon proved every lossless coder has a floor: the entropy H = โˆ’ฮฃ pยทlogโ‚‚p bits per symbol. Huffman gets close to it; perfectly random data has maximal entropy and cannot be compressed at all.
Lossless rebuilds the original bit-for-bit โ€” used where every byte matters: ZIP, PNG, FLAC, gzip. Decompress and you get back exactly what you put in.
Lossy throws away detail your senses barely notice, for far smaller files: JPEG, MP3, H.264. You can't recover the original โ€” but for photos, music and video, "close enough" buys huge savings.