{"id":217,"date":"2026-11-13T12:34:53","date_gmt":"2026-11-13T04:34:53","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-lz77-points-back-into-a-sliding-window\/"},"modified":"2026-11-13T21:53:00","modified_gmt":"2026-11-13T13:53:00","slug":"how-lz77-points-back-into-a-sliding-window","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-lz77-points-back-into-a-sliding-window\/","title":{"rendered":"How LZ77 points back into a sliding window"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>LZ77<\/strong> 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&#8217;s distance pairs.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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&#8217;s memory fixed.<\/p>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Set a window size W. The encoder and the decoder both keep the last W emitted bytes.<\/li>\n<li>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.<\/li>\n<li>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.<\/li>\n<li>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.<\/li>\n<li>Slide the window forward. Bytes that fall out of the window are no longer legal targets.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">A backward window reference is the format. LZW&#8217;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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when a match is allowed to point past the window<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Emit an offset larger than the bytes already produced<\/td>\n<td>The decoder has nothing to copy. The offset has to land inside the window behind the cursor.<\/td>\n<\/tr>\n<tr>\n<td>Forbid overlapping copies<\/td>\n<td>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.<\/td>\n<\/tr>\n<tr>\n<td>Claim the greedy longest match is the smallest encoding<\/td>\n<td>A shorter match can leave the cursor at a position where a longer match starts. Optimal parsing searches that tradeoff.<\/td>\n<\/tr>\n<tr>\n<td>Treat LZ77 and LZW as the same dictionary<\/td>\n<td>LZ77 points into a window of raw bytes. LZW emits codes for phrases in a growing table. The decoders are different.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Phrase codes that grow a table are LZW. A second-stage symbol coder is Huffman or arithmetic coding. LZ77 is the sliding-window pointer.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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 <code>aaaa<\/code> round-trips. It prints <code>aaaa<\/code>.<\/p>\n\n<pre><code class=\"language-python\">def lz77_encode(data, window=32):\n    tokens = []\n    i = 0\n    while i &lt; len(data):\n        best_len, best_off = 0, 0\n        start = max(0, i - window)\n        for j in range(start, i):\n            length = 0\n            while i + length &lt; len(data) and data[j + (length % (i - j)) if j + length &gt;= i else j + length] == data[i + length]:\n                length += 1\n            if length &gt; best_len:\n                best_len, best_off = length, i - j\n        if best_len &gt;= 2:\n            tokens.append((&quot;p&quot;, best_off, best_len))\n            i += best_len\n        else:\n            tokens.append((&quot;l&quot;, data[i]))\n            i += 1\n    return tokens\n\ndef lz77_decode(tokens):\n    out = []\n    for token in tokens:\n        if token[0] == &quot;l&quot;:\n            out.append(token[1])\n        else:\n            _, off, length = token\n            for _ in range(length):\n                out.append(out[-off])\n    return &quot;&quot;.join(out)\n\nassert lz77_decode(lz77_encode(&quot;aaaa&quot;)) == &quot;aaaa&quot;\nprint(lz77_decode(lz77_encode(&quot;aaaa&quot;)))\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\"><strong>DEFLATE<\/strong> 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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for LZ77 returns the backward window pointer and the overlapping copy that encodes a run. <strong>LZ77 compresses by replacing a repeated string with an offset and a length into a sliding window the decoder has already emitted.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,41],"tags":[],"class_list":["post-217","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-compression"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/217","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=217"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/217\/revisions"}],"predecessor-version":[{"id":616,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/217\/revisions\/616"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=217"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=217"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=217"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}