Algorithms · Visualized

Compression: LZW

Compression & Encoding

Shrink data with runs, frequencies, and clever codes.

Lempel-Ziv-Welch compression builds a dictionary of substrings seen so far on the fly, replacing repeated substrings with short dictionary codes instead of the full text. Time: O(n) average, O(n), where n is the input length worst; space: O(n) — the growing dictionary, bounded in practice by a maximum dictionary size.

Big-O: Huffman gives prefix-free optimal codes.

LZW Compression

Compression / Encoding

Lempel-Ziv-Welch compression builds a dictionary of substrings seen so far on the fly, replacing repeated substrings with short dictionary codes instead of the full text. Unlike Huffman coding, it doesn't need character frequency counts upfront — it learns patterns as it processes the input.

How LZW Works

  1. Initialize a dictionary containing every single character as its own entry (e.g. codes 0-255 for standard ASCII characters).
  2. Start building a 'current sequence' string, beginning empty, and scan through the input character by character.
  3. For each new character, check if (current sequence + new character) already exists in the dictionary.
  4. If it does, extend the current sequence to include this character and continue to the next character (without outputting anything yet).
  5. If it doesn't exist in the dictionary, output the code for the current sequence, add the new (current sequence + new character) combination to the dictionary as a new entry, and reset the current sequence to just the new character. Continue until the input is exhausted, outputting the code for whatever's left in the current sequence at the end.

LZW Worked Example

Input: ABABABA

Dictionary starts with A=1,B=2. Read 'A': current='A'. Read 'B': 'AB' not in dict → output code for 'A'(1), add 'AB'=3 to dict, current='B'. Read 'A': 'BA' not in dict → output code for 'B'(2), add 'BA'=4, current='A'. Read 'B': 'AB' IS in dict (code3) → current='AB'. Read 'A': 'ABA' not in dict → output code for 'AB'(3), add 'ABA'=5, current='A'. Read final 'A': output code for 'A'(1) at end (since 'AA' isn't found, or end of input) — actual output sequence roughly: [1,2,3,1], much shorter than 7 raw characters, and the dictionary grew to capture repeated patterns.

Compression: LZWO(n)
Dictionary-based compression that grows as it scans.
codestring
A
B
A
B
A
B
A
0123456
codes[]
Step 1 / 10
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
LZW Compression: seed the dictionary with every single character, then grow it with each new prefix.
Python · Compression Algorithms in Code
def encode(data):
    dictionary = {bytes([i]): i for i in range(256)}
    out = []
    w = b''
    for ch in data:
        wc = w + bytes([ch])
        if wc in dictionary:
            w = wc
        else:
            out.append(dictionary[w])
            dictionary[wc] = len(dictionary)
            w = bytes([ch])
    if w:
        out.append(dictionary[w])
    return out

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

LZW Time & Space Complexity

BestO(n)
AverageO(n)
WorstO(n), where n is the input length
SpaceO(n) — the growing dictionary, bounded in practice by a maximum dictionary size

When to Use LZW

  • Used in real formats like GIF images and the classic Unix 'compress' utility.
  • General-purpose lossless compression for text and data with repeating patterns, without needing to know frequencies in advance.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.