16. LZSS & LZMA
From LZ77 refinements to the engine behind 7-Zip
We covered LZ77 early in this series — the sliding-window algorithm that replaces repeated sequences with (distance, length) back-references. LZ77 was a breakthrough, but the original formulation has inefficiencies that become obvious when you try to push compression ratios to their limits.
LZSS (1982) fixes the most glaring one. LZMA (1998) builds on LZSS with range coding and Markov-chain context modeling to create one of the most powerful lossless compressors ever made — the engine behind 7-Zip, xz, and the .lzma format.
LZSS: A Smarter LZ77
LZSS (Lempel-Ziv-Storer-Szymanski, 1982) refines LZ77 in a simple but important way. Recall how LZ77 works:
LZ77 output: (distance, length, next_char)
Every token is a triple — even for literal characters that have no match. A literal like 'Q' that appears only once becomes (0, 0, Q) — three values to encode one byte. That's wasteful.
The LZSS improvement
LZSS uses a 1-bit flag to distinguish between two token types:
0 + literal byte (8 bits) — for unmatched characters
1 + (distance, length) — for back-references
Matches are only encoded as references when doing so is shorter than emitting literals.
This eliminates the waste of encoding short or non-existent matches as full triples.
LZ77 vs LZSS on "ABCXYZABCXYZ"
LZ77 output:
(0,0,A) (0,0,B) (0,0,C) (0,0,X) (0,0,Y) (0,0,Z) (6,6,_)
7 triples
LZSS output:
0 A 0 B 0 C 0 X 0 Y 0 Z 1 (6,6)
6 flag+literal pairs + 1 flag+reference pair
The LZSS encoding is smaller because each literal is just 1 + 8 = 9 bits, while each LZ77 literal triple wastes bits on the distance and length fields (which are both zero). For data with many literals (short files, high-entropy data), the savings are significant.
Minimum match length
LZSS only emits a match reference when it's actually shorter than the literal bytes it replaces. If a match reference takes B bits but the literals would take only L bits, emit literals when L ≤ B.
For typical parameters (12-bit distance, 4-bit length), a reference costs 1 + 12 + 4 = 17 bits. A literal costs 1 + 8 = 9 bits. So a match must be at least 2 bytes long to break even (2 × 9 = 18 > 17). DEFLATE's minimum match length of 3 is even more conservative because its variable-length Huffman codes add overhead.
Efficient searching with binary search trees
The original LZ77 uses brute-force search through the sliding window. LZSS implementations typically maintain a binary search tree (or suffix tree) of all substrings in the window, making match lookups O(log n) instead of O(n × m):
Window: "ABRACADABRA"
BST indexed by string content:
BRACADABRA
/ \
ABRACADABRA CADABRA
/ \ \
ABRA ACADABRA DABRA
\
ADABRA
When a new byte enters the window, insert the new substring and delete the oldest one. Each match lookup is a tree traversal — much faster than scanning the entire window.
The Road to LZMA
Between LZSS and LZMA, several innovations accumulated:
LZSS (1982) — Flag bits, minimum match length threshold, efficient tree-based search.
LZH / LHA (1988) — Combined LZSS with Huffman coding for the match/literal output. Used in the LHA archiver, hugely popular in Japan and the Amiga scene. This is essentially "LZSS + Huffman" — the same combination as DEFLATE but with LZSS instead of raw LZ77.
LZMA (1998) — Igor Pavlov's algorithm for 7-Zip. Replaces Huffman with range coding (a variant of arithmetic coding) and adds context modeling via Markov chains to predict the next bit based on recent coding decisions.
LZMA: How It Works
LZMA's architecture is deceptively simple at the top level — it's still "find matches, encode them" — but the details of how matches and literals are encoded make all the difference.
Match finding
LZMA uses a large sliding window (up to 4 GB — far larger than DEFLATE's 32 KB) with a hash chain or binary tree for fast match finding. Larger windows mean the encoder can find matches further back in the data — a huge advantage for large files with repeated structures far apart.
| Parameter | DEFLATE | LZMA |
|---|---|---|
| Window size | 32 KB | Up to 4 GB |
| Minimum match | 3 bytes | 2 bytes |
| Maximum match | 258 bytes | Unlimited (practically ~273) |
| Match finder | Hash chains | Hash chains + binary trees |
The LZMA packet format
LZMA encodes data as a stream of packets. Each packet is one of:
| Packet type | Meaning |
|---|---|
| Literal | A single byte, encoded with context-dependent range coding |
| Simple match | (length, distance) — a new back-reference |
| Short rep | Length-1 match reusing the most recent distance |
| Long rep 0–3 | Match reusing one of the four most recent distances |
The rep matches (repeated distances) are LZMA's secret weapon. In structured data, the same distances appear over and over — a struct with 32-byte records, a table with fixed column widths, source code with consistent indentation. By caching the four most recent distances and signaling which one to reuse, LZMA avoids re-encoding the same distance values repeatedly.
Range coding
Where DEFLATE uses Huffman coding, LZMA uses range coding — practically equivalent to arithmetic coding in compression ratio, but simpler to implement and patent-free.
The key difference: Huffman assigns an integer number of bits per symbol (so a symbol with probability 0.3 costs 2 bits instead of the optimal 1.74 bits). Range coding assigns fractional bits — it can spend exactly 1.74 bits on that symbol. Over millions of symbols, this adds up to 5–10% better compression.
Context modeling — the real magic
The biggest difference between LZMA and simpler LZ variants is context modeling. Instead of using a single set of probabilities for all coding decisions, LZMA uses different probability distributions depending on context — what was recently encoded.
Markov chain context
LZMA models the encoding state as a finite automaton with 12 states. Each state tracks whether recent packets were literals, matches, or rep matches. The probability of each coding decision (is the next packet a literal? a match? which rep?) depends on the current state.
On top of this, literal bytes are encoded with context from the previous byte and the match byte (the byte at the current match position). This means LZMA effectively has thousands of separate probability distributions, each tuned to a specific coding situation.
For example, after encoding a long match, the next packet is likely another match (data tends to have clusters of matchable regions). After a literal in a region with no matches, the next packet is likely another literal. The state machine captures these patterns and assigns higher probabilities to the likely packet type — which means the range coder uses fewer bits to encode it.
Optimal Parsing
Simple LZ encoders use greedy parsing: at each position, find the longest match and emit it. But greedy isn't always optimal:
Greedy vs optimal parsing
Input: ABCDEABCDXABCDE
Greedy:
Position 0: no match → literal A, B, C, D, E
Position 5: match (distance=5, length=4) "ABCD"
Position 9: literal X
Position 10: match (distance=10, length=5) "ABCDE"
Optimal:
Position 0: literal A, B, C, D, E
Position 5: match (distance=5, length=3) "ABC" ← shorter!
Position 8: literal D, X
Position 10: match (distance=5, length=5) "ABCDE" ← cheaper distance!
The optimal parser takes a shorter match at position 5 so that the match at position 10 can use distance 5 (a rep match — very cheap) instead of distance 10. The total encoding is smaller even though individual matches are shorter.
LZMA uses optimal parsing via dynamic programming. The encoder considers multiple possible ways to encode a region and picks the combination with the lowest total bit cost. This is computationally expensive (LZMA encoding is 5–20× slower than DEFLATE) but produces significantly smaller output.
The key insight: the cost of encoding a match depends on the state at the time of encoding (which rep distances are active, what the context is). A slightly shorter match now might set up a much cheaper rep match later. Optimal parsing explores these interactions.
LZMA2 and the .xz Format
LZMA2 is a wrapper around LZMA that adds:
- Multi-block encoding — the input is divided into blocks that can be compressed independently, enabling multi-threaded compression
- Uncompressed chunks — already-compressed or random data can be stored without LZMA overhead
- Dictionary resets — the dictionary can be reset between blocks, allowing the decoder to decompress from any block boundary
The .xz container format (RFC-ish, widely used on Linux) wraps LZMA2 with:
- Magic bytes and version info
- Block-based structure with index for random access
- CRC-32, CRC-64, or SHA-256 integrity checks
- Filter chains (LZMA2 can be preceded by preprocessing filters like delta or BCJ)
BCJ (Branch/Call/Jump) filters are particularly clever for executable files. Machine code contains relative jump addresses that change whenever code is moved. BCJ converts these to absolute addresses, making the repeated patterns visible to LZMA:
Before BCJ: E8 34 F2 FF FF E8 78 F1 FF FF (relative calls)
After BCJ: E8 00 10 40 00 E8 00 10 40 00 (absolute — now they match!)
This preprocessing can improve compression of executables by 5–15%.
Benchmarks: LZMA in Context
| Compressor | Canterbury corpus | Compression speed | Decompression speed |
|---|---|---|---|
| gzip -9 (DEFLATE) | 1.01 MB → 322 KB | ~20 MB/s | ~300 MB/s |
| bzip2 -9 (BWT) | 1.01 MB → 290 KB | ~10 MB/s | ~40 MB/s |
| xz -9 (LZMA2) | 1.01 MB → 260 KB | ~3 MB/s | ~100 MB/s |
| zstd -19 | 1.01 MB → 268 KB | ~5 MB/s | ~1000 MB/s |
LZMA achieves the best compression ratio but at the cost of very slow encoding. Decompression is faster than bzip2 but slower than DEFLATE or Zstandard. This profile makes LZMA ideal for:
- Software distribution — compress once (slowly), decompress many times (fast enough). Linux packages, firmware images, installers.
- Archival — maximum compression for long-term storage where encoding speed doesn't matter.
- Embedded systems — small decompressor footprint (~5 KB of code), fast enough for boot-time decompression of firmware.
Where LZMA Is Used
| System | Use case |
|---|---|
| 7-Zip | The .7z archive format uses LZMA/LZMA2 |
| xz-utils | The .xz format, standard on Linux for package compression |
| Linux kernel | Kernel image compression (one of several options) |
| Android | System image compression |
| LZMA SDK | Public domain implementation, ported to dozens of languages |
| Git | Some pack file compression implementations |
Igor Pavlov released the LZMA SDK into the public domain — no license restrictions whatsoever. This, combined with its excellent compression ratio, drove widespread adoption despite the slow encoding speed.
Try It Yourself — LZSS Encoder
Type a message and compare LZ77 and LZSS encodings side by side. The LZSS output uses flag bits (green = literal, orange = match reference) and only emits match references when they're shorter than the equivalent literals. Watch how the bit savings add up, especially on inputs with many short non-matching regions.
LZ77 Encoding
LZSS Encoding
Comparison
Key Takeaways
- LZSS improves LZ77 by using flag bits to distinguish literals from matches, eliminating waste on short/non-existent matches
- LZMA combines LZSS-style matching with range coding (fractional bits) and context-dependent probability modeling
- Rep matches (reusing recent distances) are LZMA's secret weapon for structured data
- Optimal parsing via dynamic programming finds the best combination of matches, not just the greedily longest ones
- LZMA achieves the best general-purpose compression ratios but at very slow encoding speeds
- LZMA2/xz adds multi-threading, block independence, and filter chains (BCJ for executables)
- The LZMA SDK is public domain, driving adoption in 7-Zip, xz, Linux, and Android
LZMA pushed compression ratios to their limits, but at the cost of encoding speed. What if you could get almost as good compression at 10× the speed? That's the promise of Zstandard — and it delivers by replacing range coding with the table-based ANS we covered earlier.