← All Exercises

LZW Compression with Self-Checking Decode

advancedjavascript~30min

Background

LZW is the lossless algorithm behind GIF and the historic Unix compress tool. It needs no prior statistics: the dictionary is built on the fly from the stream itself, and the decoder reconstructs it from the codes alone.

Problem

Implement LZW compression: start with a dictionary mapping every single ASCII character to its code, scan the text, and whenever the current prefix plus the next character is not in the dictionary, emit the code for the prefix, add the new sequence, and restart from the next character. Then implement the matching decoder and output both the code list and the decoded text.

Input

A JSON object {"text": string} where text contains only printable ASCII characters.

Output

A JSON object {"codes": number[], "decoded": string} where decoded must equal the input text.

Sample tests

Sample 1

Input: {"text":"abababab"}
Expected: {"codes":[97,98,256,258,98],"decoded":"abababab"}

Sample 2

Input: {"text":"TOBEORNOTTOBE"}
Expected: {"codes":[84,79,66,69,79,82,78,79,84,256,258],"decoded":"TOBEORNOTTOBE"}

Sample 3

Input: {"text":"aaaa"}
Expected: {"codes":[97,256,97],"decoded":"aaaa"}

Your solution

Learning objective

Understand dictionary-based compression, incremental dictionary growth, and why the decoder can rebuild the dictionary without transmitting it.