Greedy Token Substitution with Longest Prefix Matching
StringsAuto-graded · 22 test casesLast updated
Tests prefix-tree construction, greedy string scanning, and longest-match selection for token-based text transformation.
You are building a text tokenizer that replaces substrings with identifiers according to a replacement mapping. The mapping associates each pattern string with a replacement identifier.
Your task is to scan the input text from left to right and produce an output sequence following these rules:
- At your current position in the text, identify all patterns from the mapping that match the text starting at that position (as a prefix).
- If one or more patterns match, select the longest matching pattern, emit its corresponding identifier, and move forward by the length of that pattern.
- If no pattern matches, emit the single character at the current position and move forward by one character.
- Repeat until you've processed the entire text.
Input:
text: a string to processreplacements: a dictionary where keys are pattern strings and values are their replacement identifiers (both strings)
Output:
- A list of strings representing the tokenized output sequence
Constraints:
0 ≤ len(text) ≤ 10,0000 ≤ len(replacements) ≤ 1,000- Each pattern in
replacementshas length≥ 1and≤ 100 - Pattern strings and replacement identifiers may be empty strings (pattern length constraint applies to keys only)
- All strings consist of valid Unicode characters
- When multiple patterns of the same length match, any may be chosen (all same-length matches will have the same length, so the choice doesn't affect correctness)
Examples
Example 1
Input: tokenize_with_longest_match('abcdxyz', {'ab': '1', 'abc': '2', 'xy': '3'})
Output: ['2', 'd', '3', 'z']
Example 2
Input: tokenize_with_longest_match('aaaa', {'a': 'x', 'aa': 'y', 'aaa': 'z'})
Output: ['z', 'x']
Hints
Hint 1
A prefix tree (trie) allows you to efficiently find all patterns that match at a given position without checking each pattern separately.
Hint 2
As you traverse the trie from the current text position, each node that marks the end of a pattern represents a valid match. Keep track of the last such node encountered.
Hint 3
The greedy approach means you never backtrack—once you've chosen a match and advanced, you don't reconsider earlier positions.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is efficiently finding the longest matching pattern at each text position. Checking every pattern individually with substring comparisons would be expensive. Instead, we use a prefix tree (trie) data structure.
Building the Trie:
Construct a trie where each path from the root represents a pattern. Mark terminal nodes (where patterns end) with their replacement identifiers. We use None as a special key to store the identifier at terminal nodes, since None cannot be a text character and won't conflict with real edges.
Scanning Process:
For each position i in the text:
- Start at the trie root and walk forward character-by-character while characters match
- Each time we reach a terminal node during the walk, record its position and identifier as a potential match
- The walk continues until we can't match any more characters
- The last terminal node we encountered represents the longest match
- If we found a match, emit its identifier and jump forward by the match length
- Otherwise, emit the literal character and advance by one
Why This Works:
All patterns that match at position i share a common prefix with text[i:], so they form a single path in the trie. Walking this path visits every matching pattern in order of increasing length. By remembering the last terminal node, we naturally select the longest match.
The greedy nature means we never reconsider earlier positions—once we've consumed characters with a match, we continue from the new position.
Time Complexity: O(S + n·L), where S is the total characters across all patterns, n is the text length, and L is the maximum pattern length. Building the trie takes O(S). Each position scans at most L characters in the trie.
Space Complexity: O(S + n) for the trie and output list.
from typing import Dict, List
def tokenize_with_longest_match(text: str, replacements: Dict[str, str]) -> List[str]:
# Build a prefix tree from the replacement patterns
trie = {}
for pattern, identifier in replacements.items():
if not pattern: # Skip empty patterns to avoid infinite loops
continue
node = trie
for char in pattern:
node = node.setdefault(char, {})
node[None] = identifier
result = []
i = 0
while i < len(text):
node = trie
j = i
best_end = i
best_value = None
# Walk the trie as far as possible, tracking the longest match
while j < len(text) and text[j] in node:
node = node[text[j]]
j += 1
if None in node:
best_end = j
best_value = node[None]
if best_value is not None:
result.append(best_value)
i = best_end
else:
result.append(text[i])
i += 1
return result