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.
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.
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.
Why does any of this work, and where does it stop?