3. LZ77
Remember what you've seen before
RLE finds runs of the same character. Huffman finds that some characters appear more often than others. But there's a third, extremely powerful kind of redundancy: repetition at a distance.
In English text, the word "the" appears thousands of times. In source code, patterns
like return null; repeat over and over. In a DNA sequence, subsequences
recur constantly. What if, instead of encoding a repeated sequence from scratch, we
could just say "go back 47 bytes and copy 12 bytes from there"?
That's LZ77 — the algorithm that started the Lempel-Ziv family and is the foundation of gzip, zip, PNG, and most compression you encounter daily.
The Sliding Window
LZ77 imagines a window sliding over the data as it's processed. The window has two parts:
Already encoded Not yet encoded
◄────────────────────► ◄──────────────────────────►
┌─────────────────────┬───────────────────────────┐
│ Search Buffer │ Lookahead Buffer │
│ (e.g., 32 KB) │ (e.g., 258 bytes) │
└─────────────────────┴───────────────────────────┘
▲
Current position
(window slides →)
- Search buffer — the recently-encoded data (typically 32 KB). This is where we look for matches.
- Lookahead buffer — the upcoming data we're about to encode. We try to find this in the search buffer.
As encoding proceeds, the window slides forward. Old data falls off the left end.
The Output Format
LZ77 outputs two kinds of tokens:
- Literal — a raw byte that didn't match anything: just output it as-is
- Match — a (distance, length) pair meaning: "go back distance bytes and copy length bytes"
But this raises an immediate question: when the decoder reads the compressed stream, how does it know whether the next thing is a literal byte or a match? It's just a sequence of bits — there's no inherent boundary. The answer depends on which variant of LZ77 you're looking at. Three designs dominate, and each solves this problem differently.
How Tokens Are Represented in Bits
1. Original LZ77 (1977) — Fixed-size triples
Lempel and Ziv's original paper used the simplest possible approach: every token has the exact same format, a triple of three fixed-width fields:
┌──────────────────┬──────────────────┬──────────────┐
│ distance │ length │ next char │
│ (e.g. 12 bits) │ (e.g. 4 bits) │ (8 bits) │
└──────────────────┴──────────────────┴──────────────┘
- distance — how far back in the window the match starts (0 if no match)
- length — how many bytes to copy (0 if no match)
- next char — the literal byte that follows the match
The decoder never has to guess what kind of token it's reading — every token is the same size. A literal with no match is simply the triple (0, 0, char).
Example: encoding "ABCABC" with a 12-bit distance and 4-bit length
Position 0: no match → (0, 0, 'A') → 000000000000 0000 01000001
Position 1: no match → (0, 0, 'B') → 000000000000 0000 01000010
Position 2: no match → (0, 0, 'C') → 000000000000 0000 01000011
Position 3: match! → (3, 2, 'C') → 000000000011 0010 01000011
↑ dist=3 ↑ len=2 ↑ next='C'
Each triple is 24 bits (12 + 4 + 8). Four triples = 96 bits for 6 bytes of input. That's worse than the original! The overhead of the fixed-size triples is brutal on short inputs and non-repetitive data. Every literal costs 24 bits instead of 8.
This is simple for the decoder but wasteful. Literals pay a huge tax — 24 bits for a single byte. And the triple always includes a trailing literal, even when you'd rather just emit a long match. This motivated the next improvement.
2. LZSS (1982) — Flag bits
Storer and Szymanski's key idea: use a single bit to tell the decoder what's coming next.
Literal token:
┌───┬──────────────────────┐
│ 0 │ byte (8 bits) │
└───┴──────────────────────┘
flag the raw literal
Match token:
┌───┬──────────────────┬──────────────────┐
│ 1 │ distance │ length │
└───┴──────────────────┴──────────────────┘
flag (e.g. 12 bits) (e.g. 4 bits)
The decoder reads one bit at a time as a flag:
- Flag = 0 → read the next 8 bits as a literal byte
- Flag = 1 → read the next N bits as a (distance, length) pair
The same "ABCABC" in LZSS format (12-bit distance, 4-bit length)
0 01000001 literal 'A' (1 + 8 = 9 bits)
0 01000010 literal 'B' (1 + 8 = 9 bits)
0 01000011 literal 'C' (1 + 8 = 9 bits)
1 000000000011 0011 match(3, 3) (1 + 12 + 4 = 17 bits)
─────────────────────
Total: 44 bits
Compare: original LZ77 triples would use 96 bits for the same data. LZSS uses 44. The savings come from two places: literals cost 9 bits instead of 24, and matches don't carry a trailing literal.
When is a match worth it?
A literal costs 1 + 8 = 9 bits. A match costs 1 + 12 + 4 = 17 bits. So a match only saves space if the match length is at least 2 bytes (saving 2 × 9 − 17 = 1 bit) — really 3 bytes to make the overhead worthwhile. This is why most implementations set a minimum match length of 3. Shorter matches are emitted as literals instead.
In practice, LZSS implementations often group 8 flag bits into a single flag byte at the start of each chunk, followed by 8 tokens. This avoids the complexity of reading individual bits and aligns the literal bytes on byte boundaries, which is faster for the CPU:
┌─────────────┬────────┬────────┬────────┬──────────┐
│ flag byte │ token │ token │ token │ ... │
│ 8 flags │ 1 │ 2 │ 3 │ 4 – 8 │
└─────────────┴────────┴────────┴────────┴──────────┘
flag byte = 0b_00010010
││││││││
│││││││└─ token 1: 0 = literal
││││││└── token 2: 1 = match
│││││└─── token 3: 0 = literal
││││└──── token 4: 0 = literal
│││└───── token 5: 1 = match
││└────── token 6: 0 = literal
│└─────── token 7: 0 = literal
└──────── token 8: 0 = literal
3. DEFLATE (1993) — Unified Huffman alphabet
DEFLATE takes a completely different approach: no flag bits at all. Instead, literals and match lengths share a single Huffman-coded alphabet (values 0–285), and the Huffman code itself tells the decoder what it's looking at:
- Codes 0–255 → literal byte (the value is the byte)
- Code 256 → end of block
- Codes 257–285 → match length (followed by a separate Huffman-coded distance)
The decoder reads one Huffman code. If it decodes to 0–255, it's a literal. If it decodes to 257+, it's the start of a match. No separate flag is needed — the code value itself is the flag. This is elegant because Huffman coding assigns shorter bit sequences to frequent values, so common literals and common match lengths both get compact codes.
We'll cover DEFLATE's full encoding in detail on the DEFLATE page.
Comparing the three approaches
| Original LZ77 | LZSS | DEFLATE | |
|---|---|---|---|
| How decoder tells token types apart | It doesn't — every token is the same triple format | 1-bit flag before each token (or per group of 8) | Huffman code value: 0–255 = literal, 257+ = match |
| Cost of a literal | distance + length + byte (e.g. 24 bits) | 1 flag + 8 bits = 9 bits | Variable (Huffman-coded, often 7–9 bits) |
| Cost of a match | distance + length + byte (e.g. 24 bits) | 1 flag + distance + length (e.g. 17 bits) | Variable (Huffman-coded length + Huffman-coded distance + extra bits) |
| Used in | Original paper only | Many game/embedded formats | gzip, zip, PNG |
Full Worked Example
Input: ABCABCABCXYZXYZABC (18 bytes)
Let's walk through every position:
| Position | Search buffer | Lookahead | Best match | Output |
|---|---|---|---|---|
| 0 | (empty) | ABCABC... | No match | literal A |
| 1 | A | BCABCA... | No match | literal B |
| 2 | AB | CABCAB... | No match | literal C |
| 3 | ABC | ABCABC... | dist=3, len=6 ("ABCABC") | match (3, 6) |
| 9 | ABCABCABC | XYZXYZA... | No match | literal X |
| 10 | ...BCABCX | YZXYZAB... | No match | literal Y |
| 11 | ...CABCXY | ZXYZABC | No match | literal Z |
| 12 | ...ABCXYZ | XYZABC | dist=3, len=3 ("XYZ") | match (3, 3) |
| 15 | ...XYZXYZ | ABC | dist=15, len=3 ("ABC") | match (15, 3) |
Encoded output
literal A
literal B
literal C
match (distance=3, length=6) ← copies "ABCABC"
literal X
literal Y
literal Z
match (distance=3, length=3) ← copies "XYZ"
match (distance=15, length=3) ← copies "ABC"
Original
18 bytes
Compressed
6 literals + 3 match pairs — much less data (exact size depends on encoding format)
A Subtle but Important Detail
When length exceeds distance
Consider the match (distance=3, length=6) at position 3.
The search buffer only has "ABC" (3 bytes), yet we're copying 6 bytes.
How?
The copy proceeds one byte at a time. After copying "ABC" (the first 3 bytes), the next byte to copy is the one we just wrote — position 3, which is 'A'. Then position 4 ('B'), position 5 ('C'), and we've produced "ABCABC".
This is not a bug — it's a feature. When length > distance, the match
acts like RLE, repeating a short pattern. The match (distance=1,
length=100) starting from 'A' would produce 100 A's. LZ77 subsumes RLE
as a special case!
Decoding Is Trivially Fast
This is one of LZ77's great strengths: decoding requires no searching. The decoder simply:
-
Read a token
Check the flag bit: is it a literal or a match?
-
If literal
Output the byte and add it to the window.
-
If match (distance, length)
Go back distance bytes in the output and copy length bytes. This is just a
memcpy(with overlap handling).
Encoding is the expensive part — the encoder must search the window to find the best match. The decoder just follows instructions. This asymmetry (slow encode, fast decode) is a deliberate design choice: you compress once but decompress many times.
Finding Matches Efficiently
The naive approach — compare the lookahead against every position in the search buffer — is O(window_size × lookahead_size) per position. Too slow for large windows. Practical implementations use clever data structures:
Hash chains (what gzip uses)
Hash the first 3 bytes of the lookahead. Maintain a linked list of all positions where that same 3-byte hash occurred. Walk the chain to find the longest match. Limit the chain length for speed (this is what gzip's compression levels control).
Lazy matching
When you find a match of length N at position P, don't emit it yet. Check position P+1 — maybe there's a longer match starting there. If so, emit a literal for position P and use the longer match. This yields better compression at a small speed cost.
Optimal parsing
Consider all possible combinations of literals and matches and pick the one that produces the smallest output. This is much slower but gives the best compression. Used in high-quality compressors like Zopfli.
The Lempel-Ziv Revolution
Abraham Lempel and Jacob Ziv published this algorithm in 1977. The core insight was revolutionary: the dictionary is the data itself. You don't need to agree on a dictionary in advance or transmit one — the decoder rebuilds it from the data as it decodes.
LZ77 spawned an entire family of algorithms:
| Algorithm | Year | Key idea |
|---|---|---|
| LZ77 | 1977 | Sliding window |
| LZ78 | 1978 | Explicit dictionary (next page) |
| LZSS | 1982 | Flag bits for literals vs. matches |
| LZW | 1984 | Dictionary with single-byte init (GIF) |
| DEFLATE | 1993 | LZ77 + Huffman (gzip, zip, PNG) |
| LZMA | 1998 | LZ77 + range coding (7-Zip) |
| LZ4 | 2011 | Speed-optimized LZ77 |
| Zstandard | 2015 | LZ77 + ANS (modern standard) |
Nearly every compression tool you use today — gzip, zip, 7-Zip, zstd, Brotli, Snappy — is descended from Lempel and Ziv's 1977 paper.
LZSS: The Practical Refinement
The original LZ77 always outputs a triple: (distance, length, next_character). This wastes space when there's no match — you still output a distance and length (both 0) plus the literal.
LZSS (Storer & Szymanski, 1982) improved this with a simple idea: use a 1-bit flag before each token. Flag = 0 means a literal byte follows. Flag = 1 means a (distance, length) pair follows. This avoids the wasted overhead and is what virtually all modern LZ77-based compressors use.
Key Takeaways
- LZ77 finds repeated sequences by looking back in a sliding window of recently-seen data
- Matches are encoded as (distance, length) pairs — "copy from earlier"
- When length > distance, the copy overlaps with itself, naturally handling runs (RLE is a special case)
- Decoding is trivially fast — just follow the copy instructions. Encoding is the hard part.
- The dictionary is implicit — it's the data you've already seen. No need to transmit it.
- Foundation of gzip, zip, PNG, and virtually all modern compressors
- Combined with Huffman coding, it becomes DEFLATE
Try It Yourself — LZ77 Encoder
Type a string and adjust the window size to see LZ77 encoding step by step. The encoder uses original-style (offset, length, next character) triples.
Encoding Steps
Output Tokens
Compression Statistics
LZ77 builds its dictionary implicitly from the sliding window. But what if we built the dictionary explicitly — adding new phrases as we discover them? That's the approach of LZ78 and LZW.