LZ77 Algorithm Explained: How Dictionary Compression Works

Bottom line: LZ77 is a sliding window-based dictionary compression algorithm. The core idea is "use historical data as a dictionary, and reference back when encountering repeated content." Encoding outputs triplets (distance, length, next_char): look back distance characters to find a match of length characters, followed by one unmatched character next_char. Taking the 11-character string "abracadabra" as an example, LZ77 encoding requires only 5 triplets, demonstrating significant compression. LZ77 is a core component of DEFLATE (ZIP/GZIP/PNG) and the common ancestor of modern compression algorithms like LZSS/LZMA/LZ4. Below we start from the sliding window principle, progressively demonstrating the encoding process.

If you're not yet familiar with Huffman coding principles, we recommend first reading Huffman Coding Principle: The Foundation of Compression Algorithms.

1. What Is Dictionary Compression

Compression algorithms fall into two main schools: statistical coding (e.g., Huffman coding) assigns variable-length codewords based on character frequency; dictionary compression replaces repeated content with "pointer references." LZ77 belongs to the dictionary compression school โ€” it doesn't pre-build a dictionary table but uses processed historical data as an implicit dictionary. When encountering repeated content, it uses a "backreference pointer" to point to a previously occurring position.

SchoolCore PrincipleRepresentative AlgorithmsAdvantageDisadvantage
Statistical codingVariable-length codes by frequencyHuffman, arithmetic codingApproaches entropy boundPoor at long-range repetition
Dictionary compressionReplace repeated content with referencesLZ77, LZW, LZMAExcels at repetitive patternsIneffective on random data
Hybrid codingDictionary + statistical two-stageDEFLATE, ZSTDOverall optimalMore complex implementation
Transform codingTransform to frequency domain then quantizeDCT (JPEG), DWTHigh lossy compression efficiencyInformation loss

In practice, the most popular compression algorithms are almost all "hybrid coding" โ€” first LZ77 eliminates repetitive patterns, then Huffman applies frequency-based compression to the residuals. DEFLATE is the classic combination of LZ77 + Huffman, widely used by ZIP, GZIP, and PNG.

2. LZ77 Algorithm Principle in Detail

The core of LZ77 is the sliding window mechanism. The window is divided into two parts: the search buffer (processed historical data) and the lookahead buffer (unprocessed future data). During encoding, a segment is taken from the lookahead buffer, and the longest match is found in the search buffer โ€” if found, a triplet is output; if not, the raw character is output.

2.1 Sliding Window Structure

The sliding window size directly determines compression effectiveness โ€” larger windows allow searching more historical data, increasing match probability. Different algorithms have very different window sizes.

AlgorithmSearch BufferLookahead BufferMax Match LengthTypical Scenario
Original LZ77Few KBTens of bytes16 bytesEducational examples
DEFLATE32KB258 bytes258 bytesZIP/GZIP/PNG
LZMA8MB (configurable)273 bytes273 bytes7z/xz archival
LZ464KBUnlimitedUnlimitedReal-time compression
ZSTD8MB (max 1GB)UnlimitedUnlimitedModern general-purpose

2.2 Triplet Encoding Format

LZ77's output unit is the triplet (distance, length, next_char). The meaning of each field is shown in the table below.

FieldMeaningRange (DEFLATE)Encoding BitsExample
distanceLookback distance (how many chars back to find match)1โ€“3276815 bitdistance=10 โ†’ 10 chars back
lengthMatch length (how many consecutive chars matched)3โ€“2588 bitlength=5 โ†’ 5 chars matched
next_charCharacter following the match0โ€“2558 bitnext_char='d' โ†’ ASCII 100

The cleverness of the triplet: after a match, an extra next_char is output, ensuring the encoder always advances at least 1 character and never gets stuck. If no match is found (length=0), both distance and length are 0, and only next_char is output โ€” effectively degrading to raw character storage.

2.3 Match Finding Strategy

Match finding is LZ77's performance bottleneck โ€” taking a segment from the lookahead buffer and finding the longest match in the search buffer. Brute-force search has O(nร—m) complexity; real implementations use hash tables or suffix trees for acceleration.

Search StrategyData StructureSearch ComplexitySpace OverheadTypical Application
Brute-forceNoneO(nร—m)NoneEducational examples
Hash chainHash table + linked listO(n) averageLowzlib (DEFLATE)
Hash bucketHash table + arrayO(1) averageMediumLZ4
Suffix treeSuffix tree/arrayO(n) worst caseHighLZMA

3. Case Study: "abracadabra" Encoding Demo

Let's fully encode "abracadabra" (11 characters) with LZ77. Initial state: the search buffer is empty, and the lookahead buffer contains the entire string. We scan position by position, finding the longest match in the historical data.

Original text: a b r a c a d a b r a

Encoding process:

StepCurrent PositionLookahead ContentSearch Buffer LookupOutput TripletDescription
1Position 1abracadabraEmpty, no match(0, 0, 'a')First character, direct output
2Position 2bracadabra"a", no match for "b"(0, 0, 'b')First occurrence, direct output
3Position 3racadabra"ab", no match for "r"(0, 0, 'r')First occurrence, direct output
4Position 4acadabraFound "a" in "abr"(0, 0, 'a')"a" found but subsequent doesn't match
5Position 5cadabraNo "c" in "abra"(0, 0, 'c')First occurrence, direct output
6Position 6adabraFound "a" in "abrac"(0, 0, 'a')"a" matches but subsequent doesn't
7Position 7dabraNo "d" in "abraca"(0, 0, 'd')First occurrence, direct output
8Position 8abraLookback 7, found "abra" match(7, 4, end)Matched "abra" 4 characters

Encoding efficiency comparison:

Encoding MethodOutput UnitsBits/UnitTotal Bitsvs Original Savings
ASCII original11 chars888โ€” (baseline)
LZ77 (no match optimization)8 triplets31 (avg)248-182% (expansion)
LZ77 (optimized flags)8 units12 (avg)96-9% (slight expansion)
LZ77+Huffman8 units4.5 (avg)3659%

Result Analysis: Pure LZ77 may expand short strings (triplets take more space than raw characters), which is why LZ77 is typically combined with Huffman coding โ€” DEFLATE is LZ77 + Huffman. In the "abracadabra" case, the match at position 8 "abra" (distance=7, length=4) is the key compression point, representing 4 characters with one triplet. For longer texts with more repetitive patterns (like code files, logs), LZ77's compression effect improves significantly.

4. LZ77 Variants and Modern Evolution

Since LZ77 was proposed in 1977, it has spawned numerous variants, each optimizing a specific dimension for particular scenarios. The table below compares mainstream LZ77 family members.

AlgorithmKey ImprovementRatioCompression SpeedDecompression SpeedTypical Application
LZ77 (original)Triplet encodingLowSlowMediumEducation
LZSSFlag bits to distinguish match/literalMediumMediumFastEarly systems
DEFLATELZSS + Huffman two-stageMedium-highMediumFastZIP/GZIP/PNG
LZMALarge window + range coding + optimal parsingHighSlowMedium7z/xz archival
LZ4Sacrifices ratio for extreme speedLowVery fastVery fast (4GB/s)Real-time/kernel
LZWExplicit dictionary table (non-sliding window)MediumFastFastGIF/TIFF
ZSTDLZ77 variant + FSE + dictionary presetHighFastVery fastModern general-purpose

Looking at the evolution trend, modern algorithms (ZSTD, brotli) have significantly improved speed while maintaining high compression ratios, gradually replacing DEFLATE as the new standard. But LZ77's core idea โ€” sliding window dictionary references โ€” remains unchanged; all variants are built on this foundation.

ScenarioRecommended AlgorithmReasonReference Ratio
File archivalLZMA (xz)Highest ratio, speed not a priority70%โ€“85%
General-purposeZSTDBalances ratio and speed60%โ€“80%
Real-time transmissionLZ44GB/s decompression, ultra-low latency50%โ€“65%
Web transmissionDEFLATE/GZIPBest compatibility, all browsers support it50%โ€“70%
Image formatDEFLATE (PNG)Lossless, suitable for graphics50%โ€“75%
In-memory dataLZ4Low CPU usage, suitable for high-frequency compression50%โ€“65%

For the specific application of DEFLATE in PNG format, see PNG Compression Principle in Detail. For the difference between lossless and lossy compression, see Lossless vs Lossy Compression: Key Differences.

5. FAQ

Q1: What is the LZ77 algorithm?

LZ77 is a sliding window-based dictionary compression algorithm, proposed by Lempel and Ziv in 1977. The core idea: use previously processed data as a dictionary, and when encountering repeated content, replace the original data with a (distance, length, next_char) triplet, where distance is the lookback distance, length is the match length, and next_char is the character following the match. LZ77 is a core component of DEFLATE (ZIP/GZIP/PNG) and the ancestor of modern algorithms like LZSS/LZMA/LZ4.

Q2: What does LZ77's sliding window mean?

The sliding window is LZ77's core data structure, divided into a search buffer (processed historical data) and a lookahead buffer (unprocessed future data). During encoding, a segment is taken from the lookahead buffer, and the longest match is found in the search buffer. Typical window size is 32KB (DEFLATE standard); larger windows increase match probability but also memory overhead. The window size determines the upper limit of the maximum lookback distance.

Q3: What is the difference between LZ77 and LZ78?

LZ77 uses a sliding window as an implicit dictionary, with matched content directly referencing historical data without storing a separate dictionary; LZ78 uses an explicit dictionary table, storing seen strings as numbered dictionary entries and outputting dictionary indices during encoding. LZ77 is better suited for data with local repetition (like text), while LZ78 is better for globally repetitive data. In practice, LZ77 descendants (DEFLATE/LZMA/LZ4) are far more popular than LZ78 descendants (LZW).

Q4: Which has the highest compression ratio: LZ77, LZMA, or LZ4?

Compression ratio ranking: LZMA > LZ77 (DEFLATE) > LZ4. LZMA uses a larger window (default 8MB), better matching algorithms, and range coding, achieving the highest ratio but the slowest speed; DEFLATE uses a 32KB window + Huffman, with medium ratio and speed; LZ4 sacrifices compression ratio for extreme speed, with the lowest ratio but decompression speeds up to 4GB/s. Choice depends on the scenario: LZMA for archival, DEFLATE/ZSTD for general purpose, LZ4 for real-time.

Summary

LZ77 is the progenitor of dictionary compression algorithms. The core principle is "sliding window + triplet references": using historical data as an implicit dictionary and outputting (distance, length, next_char) triplets when encountering repeated content. Pure LZ77 may expand short texts, but combined with Huffman coding (DEFLATE), it becomes the standard compression scheme for ZIP/GZIP/PNG. The modern variant LZMA pursues ultimate compression ratio, LZ4 pursues ultimate speed, and ZSTD balances both.

Three keys to understanding LZ77: first, the sliding window determines the match range (DEFLATE 32KB, LZMA 8MB); second, the triplet is the basic encoding unit (lookback + length + next character); third, the match finding strategy determines performance (hash chains are fastest, suffix trees are optimal). The LZ77 + Huffman hybrid coding is the gold standard of modern lossless compression.

Need to Compress Files? Try SmartSlim

Built on a self-developed Rust compression engine, supporting 10 categories and 40+ formats including PDF, images, video, Office, and OFD, with local compression that keeps your data on-premises.