Advanced topics · Exercise 99 of 100

Decoding an LZW stream

LZW gives repeated sequences short dictionary codes. A decoder rebuilds the dictionary as it reads. After the first code, add the previous decoded sequence followed by the first character of the current sequence as a new entry. If the current code is the next unused one, its sequence is the previous sequence followed by its own first character.

Try it yourself

An LZW dictionary starts with A = 0 and B = 1. The next unused code is 2. Decode the stream [1, 0, 2]. What four-letter word do you recover?

One-step hint

Before looking up the final code, build its entry from the first decoded piece followed by the initial letter of the second piece.

Worked solution
  1. Code 1 gives B, then code 0 gives A. Add the previous sequence B followed by the first character A, so code 2 now means BA.
  2. Code 2 gives BA. Join the three pieces B, A and BA to recover BABA.
DSA compiler