Short answer: LZ77 compresses a stream by replacing a repeated string with a pointer into a recent window: an offset, a length, and sometimes the next unmatched character. The decoder copies those bytes from the bytes it has already emitted. A match must lie inside the window and behind the cursor, so the decoder can reproduce it without the original. Greedy longest-match parsing is the simple encoder. Optimal parsing of the match graph is slower and can be shorter. The format is the basis of DEFLATE’s distance pairs.
What the problem actually asks
Dictionary compression exploits repetition that a symbol coder such as Huffman cannot see, because Huffman codes one symbol at a time. A pointer is cheaper than the bytes it names when the match is long enough to pay for the offset and the length. The window bound is what keeps the pointer small and the decoder’s memory fixed.
A reference that points forward, or past the window, cannot be resolved by a decoder that only stores the window. The encoder has to respect the same constraint. Searching the window is a hash chain or a suffix structure. The choice changes speed and does not change the format.
What the algorithm guarantees
Every LZ77 token stream decodes to the original bytes if the encoder emitted a valid sequence of literals and backward references. Compression ratio depends on the window size, the match finder, and the parser. A greedy longest match is not always optimal: a shorter match now can enable a longer match next. Extra memory is the window. DEFLATE combines LZ77-style pointers with Huffman coding of the tokens. The bare pointers are already a compressor. The entropy coder is a second stage.
The algorithm is lossless. It does not assume a symbol alphabet beyond bytes, and it does not build an explicit dictionary of phrases the way LZW does. The dictionary is the window itself.
The working steps
- Set a window size W. The encoder and the decoder both keep the last W emitted bytes.
- At the cursor, search the window for the longest prefix of the upcoming bytes. A minimum match length, often 3, avoids pointers that cost more than the literals they replace.
- If a match exists, emit an offset and a length, and advance the cursor by the length. Otherwise emit one literal byte and advance by one.
- The decoder writes a literal or copies length bytes from offset bytes behind the write head. The copy can overlap itself, which is how a run of identical bytes is encoded.
- Slide the window forward. Bytes that fall out of the window are no longer legal targets.
A backward window reference is the format. LZW’s growing phrase dictionary is a different algorithm. Huffman coding of symbols does not replace the pointer stage when the gain comes from long repeated strings. Greedy matching is a parser, not a proof of the shortest token stream.
Approaches that look simpler and fail
| Approach | Why it fails when a match is allowed to point past the window |
|---|---|
| Emit an offset larger than the bytes already produced | The decoder has nothing to copy. The offset has to land inside the window behind the cursor. |
| Forbid overlapping copies | A run of one repeated byte is naturally a length that extends into the bytes being written. Disallowing the overlap forces those runs into literals. |
| Claim the greedy longest match is the smallest encoding | A shorter match can leave the cursor at a position where a longer match starts. Optimal parsing searches that tradeoff. |
| Treat LZ77 and LZW as the same dictionary | LZ77 points into a window of raw bytes. LZW emits codes for phrases in a growing table. The decoders are different. |
Phrase codes that grow a table are LZW. A second-stage symbol coder is Huffman or arithmetic coding. LZ77 is the sliding-window pointer.
A working example
This Python fragment points a repeated phrase back into a window of the text already emitted. An overlapping copy is allowed, which is how a run of the same byte grows. Encoding and decoding aaaa round-trips. It prints aaaa.
def lz77_encode(data, window=32):
tokens = []
i = 0
while i < len(data):
best_len, best_off = 0, 0
start = max(0, i - window)
for j in range(start, i):
length = 0
while i + length < len(data) and data[j + (length % (i - j)) if j + length >= i else j + length] == data[i + length]:
length += 1
if length > best_len:
best_len, best_off = length, i - j
if best_len >= 2:
tokens.append(("p", best_off, best_len))
i += best_len
else:
tokens.append(("l", data[i]))
i += 1
return tokens
def lz77_decode(tokens):
out = []
for token in tokens:
if token[0] == "l":
out.append(token[1])
else:
_, off, length = token
for _ in range(length):
out.append(out[-off])
return "".join(out)
assert lz77_decode(lz77_encode("aaaa")) == "aaaa"
print(lz77_decode(lz77_encode("aaaa")))
Where it is used
DEFLATE in gzip, ZIP, and PNG points back into a sliding window: that pointer is LZ77, followed by a Huffman code. A match is a length and a distance, not a new dictionary entry. LZW, used by GIF, grows a dictionary instead.
When you can drop this algorithm
Drop a pointer format when the data has no repeated substrings. A symbol coder is enough. Keep LZ77, with a defined window and a minimum match length, when repetition at a bounded distance is the redundancy.
Why this stays published
We publish this so a search for LZ77 returns the backward window pointer and the overlapping copy that encodes a run. LZ77 compresses by replacing a repeated string with an offset and a length into a sliding window the decoder has already emitted.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
