PY-47

Round-Trip a Bounded Dictionary Code Stream

  • Medium–Hard
  • Compression Mechanics
  • Python

Task

Implement encode_dictionary(tokens, initial_tokens, max_size) and decode_dictionary(codes, initial_tokens, max_size). This is a small bounded dictionary code stream. initial_tokens is a unique list of strings and every input token belongs to it. max_size is at least its length.

The initial dictionary assigns each one-token tuple its list position. The encoder follows this exact rule:

  1. Keep the longest current tuple already in the dictionary.
  2. If appending the next token produces a known tuple, extend the current tuple.
  3. Otherwise emit the current tuple's code, add the extended tuple at the next code when the dictionary is below max_size, and begin again with the next token.
  4. Emit the remaining current tuple at the end.

Return (codes, final_size). Empty tokens return ([], initial_size).

The decoder starts from the same initial dictionary. After the first valid code, each next code normally selects an existing tuple. One special code is allowed while the dictionary can still grow: a code equal to the next unused code means previous + (previous[0],). After decoding an entry, add previous + (entry[0],) when space remains.

Return (tokens, status, final_size). Use status "ok", or "invalid code at <position>" and an empty token list at the first invalid code. Empty codes are valid. Final size reports the dictionary size reached before success or failure.

Example

The bounded size changes only whether a new entry is added. Existing codes and the current match remain valid when the dictionary is full.

Your implementation

Edit solution.py and keep both signatures:

Return new lists and do not modify any input, print, or ask for input.