# LZ77 and DEFLATE: how ZIP, gzip and PNG compress

Source: https://listme.name/learn/lz77-and-deflate-how-zip-works
Published: 2026-10-10 · Updated: 2026-10-10
Level: Intermediate
Video: https://listme.name/assets/video/learn/lz77-and-deflate-how-zip-works.mp4?v=e3c084de (1:26, English captions: https://listme.name/assets/video/learn/lz77-and-deflate-how-zip-works.vtt?v=6b6e8b0a)

## Key takeaways

- LZ77 replaces a repeated stretch of text with a pointer: a distance back into the window and a length to copy.
- A pointer may overlap the text it is writing, so a long run needs only one literal and one pointer.
- DEFLATE limits distances to 32 KB and lengths to 3 to 258 bytes, then Huffman-codes the literals, lengths and distances.
- ZIP compresses each file as its own stream, while tar.gz can match repeats across files within the 32 KB window.


LZ77 replaces a repeated stretch of text with a pointer back to an earlier copy, and DEFLATE is the format that combines LZ77 with Huffman coding. ZIP, gzip and PNG all store DEFLATE data, each inside its own container. The video above shows one short phrase turning into literals and pointers in about 85 seconds; this page covers the window, the search for matches, the block format and how the containers differ.

## How a pointer reaches back

LZ77 keeps a window of text it has already written. When the text ahead matches something in the window, the encoder writes a pointer: the distance back to the match and the number of characters to copy. Otherwise it writes a literal character. The repository's demo runs the method on `red van, blue van, red van`, 26 characters long:

```
26 characters -> 15 pieces (13 literals, 2 pointers covering 13 characters)
  r e d   v a n ,   b l u e <back 10, copy 6> <back 19, copy 7>
```

The first pointer starts at character 13, the space before the second "van". It goes back ten characters, to the space after the first "red", and copies six characters, the text " van, ". The second pointer goes back nineteen characters, to the start of the line, and copies "red van". Thirteen literals and two pointers make fifteen pieces. The count of pieces is not the saving itself: the next stage shortens the pieces further.

DEFLATE's window is 32 KB. Distances run from 1 to 32,768 bytes, and a match length runs from 3 to 258 bytes (RFC 1951, sections 2 and 3.2.5). The demo is smaller on purpose: it uses a 32-character window and caps matches at 32 characters, so the example fits on screen. The minimum match of three bytes is the same as in DEFLATE.

## Why a pointer can overlap its own output

A pointer may reach into text that it is still producing. Its distance can be smaller than its length, which makes the copy repeat a pattern. A run of identical letters is the clearest case. The demo writes twelve identical letters as one literal and one pointer:

```
12 characters -> 2 pieces (1 literals, 1 pointers covering 11 characters)
  a <back 1, copy 11>
```

The pointer goes back one character and copies eleven, so each copied byte is the one written just before it. RFC 1951 gives the same case in section 3.2.3: if the last two bytes decoded are X and Y, a reference with length 5 and distance 2 adds X, Y, X, Y, X. A long run therefore costs one literal and one pointer, plus another pointer for every 258 bytes, since 258 is the longest length a single pointer can carry.

## How a compressor finds matches

Checking every earlier position for the longest match is slow on large inputs. zlib, an open-source DEFLATE library, hashes each run of three bytes and keeps, for each hash, a chain of earlier positions with that hash, newest first. For the current position it walks the chain and keeps the longest match it finds. The length of the chain is the main speed setting.

zlib's level table gives a maximum chain length of 4 at level 1 and 4096 at level 9. zlib.h names level 1 `Z_BEST_SPEED` and level 9 `Z_BEST_COMPRESSION`. Higher levels check more candidates. They can find longer matches and smaller output, and they take more time. The trade-off has limits. zlib also discards a length-3 match when it lies more than 4,096 bytes back, and RFC 1951 allows any compressor to use a smaller range of pointers than the format permits (section 3.3). The format sets the rules for decoding; the compressor chooses how hard to search.

## Blocks, fixed codes and stored blocks

A DEFLATE stream is a sequence of blocks. Each block starts with a final-block bit and a two-bit type (RFC 1951, section 3.2.3). Type 00 is a stored block: its data is copied with a length field and the one's complement of that length. Type 01 uses fixed Huffman codes that the format defines in advance. Type 10 uses dynamic codes, where the block header lists the code lengths and the decoder rebuilds the codes from them. Type 11 is an error.

Inside a compressed block, literal bytes and length codes share one alphabet of 286 symbols, numbered 0 to 285. Values 0 to 255 are literal bytes, 256 ends the block, and 257 to 285 are length codes. Some of them are followed by extra bits, and together they cover lengths from 3 to 258. Distances have their own alphabet and cover 1 to 32,768. Stored blocks exist for data that does not compress. RFC 1951 gives the worst-case expansion as 5 bytes per 32K block (section 1.1).

Each block's symbols are then coded with Huffman codes, as described in [Huffman coding explained](/learn/huffman-coding-explained). In a dynamic block the codes are built from that block's own symbol counts, so frequent literals and lengths receive the shortest bit patterns.

## Containers: ZIP, gzip, zlib and PNG

ZIP stores each file as an entry with its own local header and file data, and it lists every entry in a central directory at the end of the archive. The compression method in each entry's header says how that entry's data is stored. Method 8 means Deflated (PKWARE's APPNOTE, sections 4.3.2, 4.3.12 and 4.4.5).

A gzip file is a series of members, and each member wraps one DEFLATE stream (RFC 1952, section 2). Its header starts with the bytes 31 and 139, and its method byte is 8 for deflate. The trailer holds a CRC-32 of the data and the original size modulo 2^32.

zlib (RFC 1950) is the lighter wrapper: a two-byte header, the DEFLATE data, and an Adler-32 checksum. Its method 8 means deflate with a window up to 32K.

PNG stores a filter type byte before every scanline, then compresses the filtered rows with DEFLATE in its image data chunks. RFC 2083, the PNG specification version 1.0, says the filters are strictly lossless and can improve compressibility, and that compression method 0 is deflate with a 32K sliding window.

## ZIP and tar.gz: where matches can reach

tar combines files into one archive and does not compress them; Wikipedia lists its compression as none. A `.tar.gz` file runs gzip over that whole archive. A repeat in the second file can therefore point back into the first, as long as the distance stays within the 32 KB DEFLATE window.

ZIP works differently. Each entry is a separate stream, and a DEFLATE distance cannot refer past the beginning of its output (RFC 1951, section 3.2.3). A repeat that crosses from one ZIP entry into the next is never matched. A small file in a ZIP can only match repeats within itself.

Both formats miss any repeat more than 32 KB apart. The difference matters for similar files that sit within 32 KB of each other in the archive. For the practical choice of archive format, the [file archivers ranking](/best/file-archivers) and the guide [how to choose a file archiver](/blog/how-to-choose-a-file-archiver) compare the tools. Other algorithms, with other windows and coders, are covered in [choosing a compression algorithm](/learn/choosing-a-compression-algorithm).

## Sources

- [RFC 1951: DEFLATE Compressed Data Format Specification version 1.3](https://www.rfc-editor.org/rfc/rfc1951): windows, lengths and distances, block types, alphabets and the canonical code rule.
- [RFC 1952: GZIP file format specification version 4.3](https://www.rfc-editor.org/rfc/rfc1952): the member header, method 8, CRC-32 and ISIZE.
- [RFC 1950: ZLIB Compressed Data Format Specification version 3.3](https://www.rfc-editor.org/rfc/rfc1950): the two-byte header, method 8 and the Adler-32 trailer.
- [RFC 2083: PNG (Portable Network Graphics) Specification Version 1.0](https://www.rfc-editor.org/rfc/rfc2083): filter type bytes per scanline and compression method 0.
- [PKWARE APPNOTE: .ZIP File Format Specification, version 6.3.10](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT): local headers, the central directory and compression method 8.
- [Ziv, J. and Lempel, A. (1977). A universal algorithm for sequential data compression, IEEE Transactions on Information Theory 23(3)](https://doi.org/10.1109/TIT.1977.1055714): the 1977 paper behind LZ77.
- [zlib deflate.c](https://github.com/madler/zlib/blob/develop/deflate.c): hash chains, the level table and the length-3 distance rule.
- [zlib.h](https://github.com/madler/zlib/blob/develop/zlib.h): the level constants for best speed and best compression.
- [tar (computing), Wikipedia](https://en.wikipedia.org/wiki/Tar_%28computing%29): reference for the tar format listing compression as none.


## Video transcript

Text repeats whole phrases, not only single letters. LZ77 replaces a repeat with a pointer back to it. DEFLATE then adds Huffman codes. Take a short line with repeated words: twenty-six characters. Write a letter when nothing earlier matches. Write a pointer when something does. Go back ten and copy six. Then go back nineteen and copy seven. Twenty-six characters become fifteen pieces: thirteen letters and two pointers. LZ77 turns repeats into pointers and keeps the letters. DEFLATE packs the literals, lengths and distances into blocks. Each block then gets Huffman codes, either fixed or built for that block. A container such as ZIP, gzip or PNG wraps the result. ZIP and tar.gz both use DEFLATE, but they differ in where matches can reach. ZIP compresses each file as its own stream. Repeats across files are never matched in ZIP. In tar.gz they are, within 32 KB. Both windows are 32 KB. The tar.gz window slides over every file in turn. Pointers replace repeats, and DEFLATE gives the result short codes. Read the full guide for the containers and sources.
