Greedy Text Tokenizer with Vocabulary Trie
Data Structure DesignModel answerLast updated
Build a tokenizer that greedily matches the longest vocabulary token at each position, handling unknown characters with optional span merging.
Problem Description
Build a text tokenizer that processes input strings character by character, always selecting the longest available vocabulary match at each position. The tokenizer uses a predefined vocabulary that maps token strings to integer identifiers.
Your tokenizer must:
-
Validate the vocabulary during construction: reject empty strings and negative IDs by raising a
ValueError. -
Apply greedy longest matching: Starting from each position, find the longest vocabulary token that matches the text prefix at that position. Advance past the entire matched token.
-
Handle unmatched characters in one of two modes controlled by a
coalesce_unkflag:False: Each unmatched character becomes its own token with theunk_ididentifierTrue: Consecutive unmatched characters merge into a single token span with theunk_ididentifier
-
Work correctly with Unicode: Handle all valid Unicode code points including emoji and characters outside the basic multilingual plane.
Interface
class LongestMatchTokenizer:
def __init__(self, vocab: dict[str, int], unk_id: int = -1, coalesce_unk: bool = False):
"""
Create a tokenizer with the given vocabulary.
Args:
vocab: Maps token strings to positive integer IDs
unk_id: ID to use for unknown characters (may be negative)
coalesce_unk: Whether to merge consecutive unknown characters
Raises:
ValueError: If any vocabulary token is empty or any ID is negative
"""
pass
def tokenize(self, text: str) -> list[tuple[int, str]]:
"""
Convert input text to tokens.
Returns:
List of (token_id, matched_substring) pairs
"""
pass
Examples
Example 1: Longest match selection
vocab = {"go": 1, "going": 2, "gone": 3}
tok = LongestMatchTokenizer(vocab, unk_id=-1, coalesce_unk=False)
result = tok.tokenize("going!")
# Returns: [(2, "going"), (-1, "!")]
# "going" is chosen over "go" because it's longer
Example 2: Unknown character coalescing
vocab = {"hello": 5, "world": 6}
tok = LongestMatchTokenizer(vocab, unk_id=0, coalesce_unk=True)
result = tok.tokenize("hello... world")
# Returns: [(5, "hello"), (0, "... "), (6, "world")]
# The space and dots form one unknown span
Example 3: Greedy behavior
vocab = {"un": 10, "under": 11, "stand": 12}
tok = LongestMatchTokenizer(vocab, unk_id=0, coalesce_unk=False)
result = tok.tokenize("understand")
# Returns: [(11, "under"), (12, "stand")]
# Not [(10, "un"), ...] because "under" is the longest match at position 0
Constraints
- Vocabulary size: 1 to 100,000 tokens
- Token length: 1 to 100 Unicode code points
- Input text length: 0 to 500,000 code points
- Token IDs: integers in range [0, 10^9]
- Target complexity: O(N × M) where N is text length and M is maximum token length
Hints
Hint 1
A trie structure allows efficient lookup of all vocabulary tokens that could start at a given position
Hint 2
Track the last complete token found while walking the trie to identify the longest match
Hint 3
When coalescing unknowns, accumulate characters until you find a position where a vocabulary match succeeds
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
The core challenge is efficiently finding the longest vocabulary token at each position. A trie (prefix tree) is the ideal structure because it lets us check all possible match lengths in a single traversal.
Algorithm Overview
1. Build a trie from the vocabulary
Insert each token into the trie, marking terminal nodes with their associated ID. Each trie node is a dictionary mapping characters to child nodes, with a special marker for "token ends here."
2. For each position in the input text
Walk down the trie following the characters. Track the last position where we saw a complete token (terminal node). This gives us the longest match.
- If a match exists: emit the token and jump past it
- If no match exists: handle as unknown character(s)
3. Unknown character handling
- Without coalescing: emit each unmatched character immediately as
(unk_id, char) - With coalescing: accumulate unmatched characters into a buffer. Flush the buffer only when a vocabulary match is found or when reaching the end of input.
Why This Works
Correctness of longest match: As we walk the trie from position i, we see every prefix of the remaining text that exists in the vocabulary. By remembering the deepest terminal node we passed, we capture the longest such prefix. When the walk terminates (no matching edge), we know no longer match exists.
Greedy is not optimal: With vocabulary {"ab", "abc", "cd"} and text "abcd", we'll emit abc then d (unknown), not the alternative ab, cd. This is the specified greedy behavior—we commit to the longest match at each position without lookahead.
Coalescing correctness: A character enters the unknown span only if no vocabulary token begins at that position. We probe each position exactly once. The first successful probe ends the span, ensuring maximal runs of unmatched positions.
Complexity Analysis
Time: O(N × M) where N is text length and M is the longest token in vocabulary
- Each position initiates one trie walk
- Each walk checks at most M characters
- Dictionary lookups in the trie are O(1) average case
Space: O(V × L) for the trie, where V is vocabulary size and L is average token length, plus O(N) for output
Implementation Details
Vocabulary validation: Check all entries before building any state. This ensures the object is never partially initialized.
Unicode handling: Python strings are sequences of Unicode code points, so indexing and iteration handle multi-byte characters automatically. No special encoding logic needed.
Trie terminal marker: Use None as the key for "token ends here" in node dictionaries. It cannot collide with any character string.
Coalescing state: Track the start index of the current unknown span. A value of -1 means no span is active. Don't forget to flush any pending span after the main loop completes.
Complete Solution
class LongestMatchTokenizer:
_TERMINAL = None # marker for token completion at a node
def __init__(self, vocab: dict[str, int], unk_id: int = -1, coalesce_unk: bool = False):
# Validate all entries before modifying any state
for token_str, token_id in vocab.items():
if not token_str:
raise ValueError(f"Token cannot be empty")
if token_id < 0:
raise ValueError(f"Token ID must be non-negative, got {token_id}")
self.unk_id = unk_id
self.coalesce_unk = coalesce_unk
self._root = {}
# Build trie
for token_str, token_id in vocab.items():
node = self._root
for char in token_str:
if char not in node:
node[char] = {}
node = node[char]
node[self._TERMINAL] = token_id
def _find_longest_at(self, text: str, start: int) -> tuple[int, int]:
"""Return (match_length, token_id) for longest match at position start."""
node = self._root
longest_len = 0
longest_id = -1
pos = start
while pos < len(text):
char = text[pos]
if char not in node:
break
node = node[char]
pos += 1
# Check if this forms a complete token
if self._TERMINAL in node:
longest_len = pos - start
longest_id = node[self._TERMINAL]
return longest_len, longest_id
def tokenize(self, text: str) -> list[tuple[int, str]]:
result = []
i = 0
unk_span_start = -1 # -1 means no active unknown span
while i < len(text):
match_len, token_id = self._find_longest_at(text, i)
if match_len > 0:
# Found a vocabulary match
if unk_span_start >= 0:
# Flush any pending unknown span first
result.append((self.unk_id, text[unk_span_start:i]))
unk_span_start = -1
result.append((token_id, text[i:i + match_len]))
i += match_len
else:
# No match at this position
if self.coalesce_unk:
if unk_span_start < 0:
unk_span_start = i
i += 1
else:
result.append((self.unk_id, text[i]))
i += 1
# Flush any trailing unknown span
if unk_span_start >= 0:
result.append((self.unk_id, text[unk_span_start:]))
return result
Common Mistakes
- Forgetting to flush the final unknown span when coalescing is enabled
- Checking only one match length instead of finding the longest
- Not validating vocabulary before building the trie
- Byte-level tokenization instead of code-point level, corrupting Unicode
- Stopping at the first trie terminal instead of continuing to find longer matches
Follow-Up Extensions
Streaming input: When text arrives in chunks, a token might span a boundary. Keep a buffer of up to M-1 characters (where M is max token length) between chunks. Only emit tokens when the walk terminates before the buffer end, or when you have enough lookahead to guarantee completion.
Case-insensitive matching: Normalize both vocabulary and input to lowercase during insertion and lookup. Store original-case tokens separately if needed for output.
Ambiguity resolution: If multiple tokens of the same length match, the current approach takes whichever is found first in the trie. You could add a priority field to terminal nodes to break ties deterministically.