KatInterview

Greedy Text Tokenizer with Vocabulary Trie

Data Structure DesignModel answer
HardModel answerData Structure Designtriestring-matchingtokenization

Last 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:

  1. Validate the vocabulary during construction: reject empty strings and negative IDs by raising a ValueError.

  2. 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.

  3. Handle unmatched characters in one of two modes controlled by a coalesce_unk flag:

    • False: Each unmatched character becomes its own token with the unk_id identifier
    • True: Consecutive unmatched characters merge into a single token span with the unk_id identifier
  4. 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