Algorithms · Visualized

Compression & Encoding

Compression & Encoding

Shrink data with runs, frequencies, and clever codes.

Big-O: Huffman gives prefix-free optimal codes.

📖 Family Introduction

Compression & Encoding

Represent the same information in fewer bits — losslessly wherever it matters.

Compression encodes data using its redundancy. Run-length encoding replaces repeats with counts (AAAA → 4A) and wins only on long runs. Huffman coding assigns short bit codes to frequent symbols and longer codes to rare ones, building an optimal prefix-free code tree with a greedy merge of the two least-frequent nodes — “prefix-free” means no code is a prefix of another, so the bitstream decodes without separators. LZW goes further: it learns a dictionary of substrings during a single scan and emits dictionary indices, adapting to the data without transmitting a table (this is GIF’s core). Lossy methods (JPEG, MP3) additionally discard information humans perceive least.

The general recipe

  1. Measure the redundancy: symbol frequencies, repeated runs, or repeated substrings.
  2. Choose the model: run-length for streaks, frequency codes (Huffman) for skewed alphabets, dictionary growth (LZW) for repeated substrings.
  3. Encode: emit counts, per-symbol bit codes, or dictionary indices.
  4. Decode by replaying the same construction — Huffman from the stored table, LZW by rebuilding the dictionary identically.
  5. Verify round-trip equality (lossless) and measure the ratio against the raw size.

Vocabulary you'll meet everywhere here

Lossless / lossy
bit-exact reconstruction versus perceptually-close reconstruction
Prefix-free code
no codeword extends another, enabling unambiguous concatenation (Huffman)
Entropy
the theoretical minimum average bits per symbol for a distribution — Huffman approaches it
Dictionary
substring → index mapping grown during the scan (LZW)
Compression ratio
compressed size ÷ original size; some data (random bits) is incompressible

Where this family shows up

  • File formats: ZIP (DEFLATE = LZ77 + Huffman), GIF (LZW), PNG (filters + DEFLATE)
  • Network protocols header compression, database columnar encodings
  • Text message packing and DNA-sequence storage where exactness is mandatory

Common pitfalls

  • Forgetting to store the code table (Huffman) — the decoder cannot rebuild the tree without it
  • RLE on data without runs can double the size (each run of 1 becomes “1x”) — guard the format
  • LZW dictionary resetting: encoder and decoder must stay perfectly in sync
  • Comparing compressed sizes without counting the header/metadata overhead
Python · Compression Algorithms in Code
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 codes

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.