KatInterview

Greedy Token Substitution with Longest Prefix Matching

StringsAuto-graded · 22 test cases
HardAuto-gradedStringstriegreedystring-processing

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

  1. At your current position in the text, identify all patterns from the mapping that match the text starting at that position (as a prefix).
  2. If one or more patterns match, select the longest matching pattern, emit its corresponding identifier, and move forward by the length of that pattern.
  3. If no pattern matches, emit the single character at the current position and move forward by one character.
  4. Repeat until you've processed the entire text.

Input:

  • text: a string to process
  • replacements: 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,000
  • 0 ≤ len(replacements) ≤ 1,000
  • Each pattern in replacements has length ≥ 1 and ≤ 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.