Text Substitution with Whole-Word Match and Longest-Prefix Priority
StringsAuto-graded · 23 test casesLast updated
Apply a phrase-to-replacement map on the original text in one pass, respecting whole-word boundaries and preferring longer matches.
You are given a string document and two equal-length arrays find and replace_with. Each find[i] should be substituted with replace_with[i] wherever it appears in the document.
Your task is to return the transformed document after applying all substitutions simultaneously—that is, every match is determined against the original text, so replacements already inserted cannot themselves be matched or altered by later rules.
Rules
- Case-sensitive literal matching. Match each phrase exactly, including any internal spaces.
- Whole-word boundaries. A valid match must not be immediately preceded or followed by a word character. Word characters are ASCII letters (
a-z,A-Z), digits (0-9), and underscore (_). All other characters—including spaces, punctuation, and the start or end of the string—are non-word. - Longest match wins. When scanning left to right, if multiple phrases can match starting at the current position (and all satisfy the boundary requirement), choose the one that spans the most characters. Advance past the entire matched span and continue scanning from there.
- One-pass processing. Each position in the original document is examined exactly once. Text inserted by a replacement is never re-scanned.
- Unmatched characters are copied verbatim.
Constraints
0 ≤ len(document) ≤ 10,0000 ≤ len(find) ≤ 100len(find) == len(replace_with)- Each phrase in
findis non-empty, begins and ends with a word character, and is unique. - Each string in
replace_withmay be empty (deletes the phrase) or arbitrarily long. - Each phrase and replacement has at most 100 characters.
- All input is ASCII.
- Distinct phrases of equal length will never match the exact same span simultaneously.
Examples
Example 1
Input: apply_substitutions('Person One emailed Person.', ['Person', 'Person One'], ['word', 'name'])
Output: 'name emailed word.'
Example 2
Input: apply_substitutions('red redwood blue', ['red', 'blue'], ['blue', ''])
Output: 'blue redwood '
Example 3
Input: apply_substitutions('alpha beta alpha', ['alpha', 'alpha beta'], ['X', 'Y'])
Output: 'Y X'
Hints
Hint 1
Sequential string replacements cascade: text inserted by one rule can be matched by another. Keep the scan index on the original text and write output to a separate buffer.
Hint 2
Build a trie of all phrases and walk it from each candidate start position. As you walk, record every phrase endpoint that also satisfies the right boundary condition; the last one recorded is the longest.
Hint 3
A phrase like 'cat' inside 'category' should not match if 'y' immediately follows. Check that the character after the match (if any) is not a word character before accepting the match.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Naively calling text = text.replace(a, b) for each phrase fails for two reasons:
- Cascading. If one replacement produces text that matches another phrase, it will be replaced again, violating the simultaneity requirement.
- Priority. Replacing shorter phrases first can destroy longer phrases that contain them.
The solution is to maintain a scan index on the original document and write output to a separate buffer. At each position:
- Check whether we are at a valid left word boundary (either the start of the string, or the previous character is not a word character).
- If so, attempt to match every phrase that starts at this position and also ends at a valid right boundary (either the end of the string, or the character immediately after is not a word character).
- Among all valid matches, choose the longest one. Emit its replacement and advance the scan index past the matched span in the original text.
- If no match is found, copy the current character and advance by one.
Because the scan index only moves forward through the original string, inserted text is never re-examined.
Data Structure: Trie
To efficiently find all phrases that start at position i, we build a trie (prefix tree) from the find array. Each leaf in the trie stores the corresponding replacement using a sentinel key '' (which cannot collide with any single-character key).
From position i, we walk the trie character by character. Whenever we reach a node that marks the end of a phrase (has the '' key), we check the right boundary. If valid, we record this as a candidate match. The trie walk naturally visits longer prefixes after shorter ones, so the last recorded match is the longest.
This handles a subtle edge case: suppose "cat" and "category" are both phrases, and the text is "category". The trie walk will first see "cat" as a terminal, but the next character 'e' is a word character, so "cat" is rejected. The walk continues and may find "category" valid (if it ends at a boundary). If instead the text is "cat!", then "cat" is recorded and used, because '!' is not a word character.
Why It Works
- Simultaneity: Every match decision inspects only the original
document, never the output buffer. Boundary checks usedocument[i-1]anddocument[j], so replacement text cannot influence any match. - Longest-match: The trie walk enumerates every prefix of
document[i:]that is also a phrase. Among those with valid right boundaries, we keep the one ending furthest to the right—exactly the longest valid phrase. - One-pass: After emitting a replacement, we jump the scan index to the end of the matched span. That position is either end-of-string or a non-word character (because the match had a valid right boundary), so the next iteration correctly checks for a new left boundary.
Complexity
- Time: Building the trie takes O(F), where F is the total length of all phrases. Scanning the document takes O(N · L), where N is the length of the document and L is the maximum phrase length (at most 100). Each starting position walks at most L trie edges. With N ≤ 10,000 and L ≤ 100, this is well within limits. Copying replacements into the output adds O(output size).
- Space: O(F) for the trie, plus O(output size) for the result buffer. The output length can be larger than the input if replacements are long.
An Aho–Corasick automaton would reduce the scan to O(N + number of matches), but given these constraints the trie is simpler and sufficient.
Reference Solution
from typing import List
def apply_substitutions(document: str, find: List[str], replace_with: List[str]) -> str:
def is_word_char(ch: str) -> bool:
return ('a' <= ch <= 'z' or 'A' <= ch <= 'Z' or
'0' <= ch <= '9' or ch == '_')
# Build a trie of phrases; '' marks a terminal and holds the replacement.
root = {}
for phrase, repl in zip(find, replace_with):
node = root
for c in phrase:
node = node.setdefault(c, {})
node[''] = repl
output = []
i = 0
length = len(document)
while i < length:
match_end = -1
match_repl = None
# Only try matching if we are at a left word boundary.
if i == 0 or not is_word_char(document[i - 1]):
node = root
j = i
# Walk the trie as far as possible.
while j < length and document[j] in node:
node = node[document[j]]
j += 1
# If this node ends a phrase and the right boundary is valid, record it.
if '' in node and (j == length or not is_word_char(document[j])):
match_end = j
match_repl = node['']
if match_end != -1:
output.append(match_repl)
i = match_end
else:
output.append(document[i])
i += 1
return ''.join(output)