4. LZ78 & LZW

Build a dictionary as you go

LZ77 keeps a sliding window of recent data and searches it for matches. It works well, but the window has a fixed size — once data slides out the back, it's gone forever. A repeated phrase that appeared 100 KB ago? Forgotten.

In 1978, Lempel and Ziv published a different approach: instead of an implicit window, build an explicit dictionary of phrases. Every new phrase you encounter gets added to the dictionary and can be referenced at any point in the future. This is LZ78.

How LZ78 Works

  1. Start with an empty dictionary

    Entry 0 represents the empty string.

  2. Read input symbols and find the longest dictionary match

    Find the longest prefix of the remaining input that matches an existing dictionary entry.

  3. Output (index, next character)

    Output the dictionary index of the match and the next character after it.

  4. Add a new dictionary entry

    The matched phrase + the next character becomes a new entry.

  5. Repeat

    Continue from the character after the one you just output.

Worked Example: AABABCAABABC

Step Remaining input Longest match Output New dictionary entry
1AABABCAABABC(empty)(0, A)1: A
2ABABCAABABCA (entry 1)(1, B)2: AB
3ABCAABABCAB (entry 2)(2, C)3: ABC
4AABABCA (entry 1)(1, A)4: AA
5BABC(empty)(0, B)5: B
6ABCABC (entry 3)(3, —)—

The dictionary grows with each step. By step 6, the phrase "ABC" is already in the dictionary, so it's encoded with a single index.

LZW: The Practical Improvement

In 1984, Terry Welch improved LZ78 with two key changes that make it simpler and more efficient:

LZW's two improvements over LZ78

  1. Initialize the dictionary with all single characters (entries 0–255 for byte data). This means we never need to output raw characters — only dictionary indices.
  2. Output only the index — no extra character. The new dictionary entry is the current match + the first character of the next match.

LZW Algorithm

  1. Initialize dictionary with all single-byte entries (0–255)

    Every possible single byte already has an entry.

  2. Read input, find the longest match in the dictionary

    Since all single bytes are in the dictionary, you'll always match at least one character.

  3. Output the index of the match

    Just the index — no extra character.

  4. Add a new entry: current match + next input character

    This extends the dictionary with a new, longer phrase.

  5. Restart matching from the next input character

    (Not from the character after — from the character that didn't match.)

LZW Encoding Walkthrough

Input: ABABABABAB

Initial dictionary: A = 0, B = 1 (simplified to just these two characters)

Step Current match Next char Output New entry
1AB0 (A)2: AB
2BA1 (B)3: BA
3ABA2 (AB)4: ABA
4BAB3 (BA)5: BAB
5AB—2 (AB)—

Output stream: 0, 1, 2, 3, 2

5 indices encoding 10 characters. As the dictionary grows, longer and longer phrases get single-index codes.

Notice how the dictionary learns the structure of the data. After seeing "AB" and "BA", it starts matching "ABA" and "BAB" — increasingly long phrases encoded with a single index.

LZW Decoding — The Clever Part

The decoder builds the exact same dictionary as the encoder, one step behind. It reads each index, looks it up, outputs the string, and adds a new entry.

Decoding: 0, 1, 2, 3, 2

Initial dictionary: 0 = A, 1 = B

Step Read index Output New entry (prev output + first char of current output)
10A— (no previous yet)
21B2: A + B = AB
32AB3: B + A = BA
43BA4: AB + B = ABA
52AB5: BA + A = BAB

Decoded output: A + B + AB + BA + AB = ABABABABAB ✓

The Tricky Edge Case

When the decoder sees an index it hasn't added yet

Sometimes the encoder outputs an index for an entry it just created. The decoder is one step behind, so it hasn't created that entry yet!

This happens when the input has the pattern cScSc where cS is already in the dictionary and c is a single character. The encoder adds cSc and immediately uses it.

The decoder handles this with a simple rule: if you see an unknown index, the string is the previous output + the first character of the previous output. This always works because the only way this situation arises is when the new entry starts the same way as the previous one.

Variable-Width Codes

The dictionary starts small (256 entries for byte data) and grows with each step. The indices need enough bits to address every entry:

Dictionary size Bits per index
257–512 9 bits
513–1024 10 bits
1025–2048 11 bits
2049–4096 12 bits

Both encoder and decoder know exactly when to increase the code width (when the dictionary size crosses a power-of-2 boundary), so no signaling is needed.

Eventually the dictionary fills up (typically capped at 4096 entries / 12 bits). Options at that point:

  • Freeze — stop adding entries, keep using the existing dictionary
  • Clear — send a special "clear code" and reset the dictionary (GIF does this)
  • LRU eviction — remove least-recently-used entries to make room

The GIF Connection and the Patent Wars

LZW became famous (and infamous) through the GIF image format. CompuServe chose LZW for GIF in 1987, and it became the web's favorite image format for simple graphics and animations.

The problem: Unisys held a patent on LZW (filed by Welch in 1983). In the mid-1990s, Unisys began enforcing the patent, demanding royalties from anyone creating software that generated GIF files.

The backlash was enormous. The open-source community responded by creating PNG — a patent-free image format using DEFLATE (LZ77 + Huffman) instead of LZW. The "Burn All GIFs" campaign pushed adoption of PNG.

The LZW patents expired in 2003–2004. By then, PNG was well-established. The episode remains one of the most significant patent disputes in software history and a cautionary tale about patenting compression algorithms.

LZ78 vs LZ77 — Tradeoffs

LZ77 (sliding window) LZ78/LZW (explicit dictionary)
Dictionary Implicit — it's the window itself Explicit — grows as encoding proceeds
Memory Bounded (window size) Can grow large; needs a cap
Back-references Only recent data (within window) Any previously seen phrase
Match finding Requires searching the window Hash table lookup — fast
Modern status Dominant (gzip, zstd, etc.) Niche (GIF, legacy systems)

In practice, LZ77-based schemes have won for general-purpose compression. DEFLATE, LZMA, and Zstandard all use LZ77-style matching. LZW remains important in specific formats (GIF) and as a conceptual stepping stone.

Try It Yourself — LZW Encoder & Decoder

Type a string and watch LZW build its dictionary in real time. Switch to Decode mode to see the decoder reconstruct the original from just the index stream — including the tricky edge case when it encounters a code it hasn't added yet.

Output Codes

Encoding Steps

Dictionary

Statistics

Key Takeaways

  • LZ78 builds an explicit dictionary of phrases from the input, adding a new entry at each step
  • LZW improves LZ78 by pre-initializing the dictionary with all single-byte entries and outputting only indices
  • Both encoder and decoder build the same dictionary in lockstep — no need to transmit it
  • The "code not in dictionary" edge case is the trickiest part — handle it by repeating the previous output's first character
  • Used in GIF, TIFF, and the Unix compress command
  • Patent disputes over LZW led to the creation of PNG and DEFLATE's dominance

We've now seen two families of techniques: entropy coding (Huffman) and dictionary-based matching (LZ77, LZW). What happens when you combine them? That's DEFLATE — the most widely used compression algorithm in the world.