An LZ78 encoder starts with an empty phrase at index zero. At each input position it follows the longest phrase already present in a trie, then emits that phrase's index plus the next unseen symbol and inserts the extended phrase. If the input ends exactly on an existing phrase, this format emits a final token with an empty symbol. The decoder recreates the same phrase table in token order and concatenates decoded phrases. This is a dictionary coding model over Python characters; it does not pack integers into bytes, carry a wire header, or reset a bounded dictionary. The encoder and decoder must agree on the empty-final-token rule.
LZ78 phrase tries: emit dictionary index and next symbol
Operational case
The incident string cabacabacaba produces seven phrase tokens, and decoding those tokens returns the original twelve-character string. The dictionary grows only when a token includes a new symbol; the final empty-symbol token reuses an earlier phrase without adding another one. A decoder must reject a phrase index that has not yet been defined, or corrupted input could reference data from the future. Empty text produces no tokens. The output size in bytes depends on how phrase indexes and symbols are serialized, so counting pairs alone is not a compression-ratio claim.
Working Python program
class PhraseNode:
def __init__(self, phrase_id):
self.phrase_id = phrase_id
self.children = {}
def encode_incident(text):
root = PhraseNode(0)
next_id = 1
encoded = []
position = 0
while position < len(text):
cursor = root
while position < len(text) and text[position] in cursor.children:
cursor = cursor.children[text[position]]
position += 1
if position == len(text):
encoded.append((cursor.phrase_id, ""))
break
symbol = text[position]
encoded.append((cursor.phrase_id, symbol))
cursor.children[symbol] = PhraseNode(next_id)
next_id += 1
position += 1
return encoded
def decode_incident(encoded):
phrases = [""]
output = []
for position, (phrase_id, symbol) in enumerate(encoded):
if not 0 <= phrase_id < len(phrases) or len(symbol) > 1:
raise ValueError("invalid phrase token")
if symbol == "" and (phrase_id == 0 or position != len(encoded) - 1):
raise ValueError("only final nonempty phrase may omit symbol")
phrase = phrases[phrase_id] + symbol
output.append(phrase)
if symbol:
phrases.append(phrase)
return "".join(output)
if __name__ == "__main__":
incident = "cabacabacaba"
tokens = encode_incident(incident)
print(tokens)
print(decode_incident(tokens))Output
[(0, 'c'), (0, 'a'), (0, 'b'), (2, 'c'), (2, 'b'), (4, 'a'), (3, 'a')]
cabacabacabaTime, space, and tradeoff
Encoding traverses each input character once along trie edges with expected dictionary lookup, giving O(N) expected work and O(N) nodes or tokens for input length N. The simple decoder reconstructs phrases by Python string concatenation, which can copy long prefixes repeatedly and cost O(N squared) character work in a bad case. Its token list and phrase table also occupy O(N) references plus phrase strings. A production codec would define framing, symbol encoding, dictionary limits, and corruption handling. A prefix trie indexes search terms; this phrase trie instead gives each newly seen text phrase a numeric code.
Common Mistakes
- Do not add a dictionary phrase for an empty final symbol.
- Do not decode a forward reference to a phrase that has not been created.
- Do not call token count a byte-level compression ratio.
- Do not mix character offsets with encoded byte positions.
Connected lessons
- Trees and Heaps
- Data Structures
- Tries: make prefix search distinct from complete-key lookup
- Compressed tries: split shared edge labels at the divergence
- Front-coded lexicons: store shared prefixes within sorted term blocks
- Projects
- Quizzes
Compare its query and update boundary with Segment-tree stabbing indexes: list intervals active at one point, Huffman trees: assign prefix codes from symbol frequencies, Condensation DAGs: compress directed cycles before path queries, then complete the structure audit and decision quiz.
