Anthropic Screening Question: Longest-Match Tokenization with a Trie

atullchaurasia · x · 2026-11-29

A coding problem reportedly used in Anthropic's screening: given a text and a dictionary of <key>:<id> entries (unique keys, text length and dictionary size up to 10^9), split the text into tokens. At each position, pick the longest dictionary key that starts there, output its id, and skip past it; if no key matches, emit the single character as a literal and advance by one.

The suggested approach builds a trie over all keys, storing each key's id at its end node, then scans text left to right: at each position follow the trie as deep as the text matches, tracking the last node where a complete key ended. Output that key's id and jump past it, otherwise emit the current character. Time is O(N×L) where N is text length and L the longest key length; space is O(S+N) for the trie plus output. Follow-ups cover handling a dictionary too large for memory and compressing trie space when keys share prefixes.

Original post →

More from coding & agent

coding & agent channel →