Short answer: LZW compresses by emitting codes for phrases in a dictionary that starts as the alphabet and grows by one new phrase per step. The encoder finds the longest dictionary phrase that matches the upcoming bytes, emits its code, and adds the phrase plus the next input byte as a new phrase. The decoder rebuilds the same dictionary from the code stream alone, with one special case when the code names a phrase the decoder is in the middle of creating. GIF and the old compress program use this scheme.
What the problem actually asks
LZ77 points at raw bytes in a window. LZW points at phrase numbers. The dictionary is implicit in the code stream, so the compressor does not send the phrases themselves. Both sides start from the same alphabet and apply the same add-one-phrase rule, so they stay in step as long as the special case is handled.
The special case happens when the encoder emits a code for a phrase the decoder has not yet inserted, which occurs when the phrase is the one the decoder is just about to learn. The decoder builds it as the previous phrase plus its own first character. Ignoring that case drops a byte or inserts the wrong one.
What the algorithm guarantees
A correct encoder and decoder reproduce the input exactly, including the special case. The dictionary size is capped, often at 4096 entries for a 12-bit code. When the table is full, an implementation either stops adding phrases or clears the table with a reset code. GIF’s clear code is that reset. Time is linear in the input for a dictionary with a constant-time longest-match structure, typically a trie. Extra memory is the dictionary.
The algorithm is lossless and byte-oriented in the usual GIF form. It is not a sliding-window pointer, and it is not an entropy coder. A later bit packer may still Huffman-code the phrase codes. The basic LZW stream is the phrase codes themselves.
The working steps
- Initialize the dictionary with a code for every single-byte symbol. Set the next new code to the next free number.
- The encoder reads the longest phrase w that is in the dictionary. It emits the code of w. Let k be the next input byte. Insert w concatenated with k, if the table is not full.
- Start the next phrase at k, which is the overlap between consecutive dictionary inserts.
- The decoder emits the phrase for the received code. If the code is the one about to be assigned, the phrase is the previous phrase plus the previous phrase’s first byte.
- Otherwise the new dictionary phrase is the previous phrase plus the first byte of the phrase just decoded. A clear code resets the dictionary to the alphabet.
The special case is required for correctness, not as an optimization. LZ77 is the alternative dictionary that never sends a code the decoder has not already materialized as raw bytes. A full table that keeps accepting new codes without growing will overwrite phrases and desynchronize the decoder unless both sides share the eviction rule.
Approaches that look simpler and fail
| Approach | Why it fails when the decoder rejects a code it has not inserted yet |
|---|---|
| Treat the next free code as an error | That code is legal in the special case. The phrase is the previous output plus its first byte. |
| Insert the new phrase before emitting the current code, on only one side | The encoder and the decoder must add phrases at the same logical moment. A one-sided reorder desynchronizes the table. |
| Forget the clear code when the bit width is exhausted | The encoder will emit a code the decoder cannot store, or it will wrap. GIF resets. A compatible decoder has to reset on the same code. |
| Describe the format as an LZ77 window | There is no offset and length. There is a phrase table grown from the alphabet. |
Window pointers are LZ77. Entropy coding of whatever tokens come out is Huffman or arithmetic coding. LZW is the growing phrase-code dictionary.
A working example
This Python fragment grows a dictionary of phrases. The decoder accepts the code that is not inserted yet: it is the previous phrase plus that phrase’s first byte. Encoding and decoding ABABABA round-trips. It prints ABABABA.
def lzw_encode(data):
table = {chr(i): i for i in range(256)}
next_code = 256
w = ""
codes = []
for ch in data:
wc = w + ch
if wc in table:
w = wc
else:
codes.append(table[w])
table[wc] = next_code
next_code += 1
w = ch
if w:
codes.append(table[w])
return codes
def lzw_decode(codes):
table = {i: chr(i) for i in range(256)}
next_code = 256
prev = table[codes[0]]
out = [prev]
for code in codes[1:]:
if code in table:
entry = table[code]
elif code == next_code:
entry = prev + prev[0]
else:
raise SystemExit("bad code")
out.append(entry)
table[next_code] = prev + entry[0]
next_code += 1
prev = entry
return "".join(out)
assert lzw_decode(lzw_encode("ABABABA")) == "ABABABA"
print(lzw_decode(lzw_encode("ABABABA")))
Where it is used
GIF and the old Unix compress tool encode with LZW: the dictionary grows by one phrase each time a code is emitted. TIFF has used the same code. DEFLATE replaced that style in ZIP with LZ77 plus Huffman.
When you can drop this algorithm
Drop a homemade LZW variant that omits the special case. Implement that case, or use a format whose specification you can test against known files. Keep LZW when the container, such as GIF, already chose it.
Why this stays published
We publish this so a search for LZW returns the growing phrase dictionary and the special case the decoder must accept. LZW compresses by emitting codes from a dictionary both sides grow in lockstep, including the case where the code being decoded is the phrase just being created.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
