Split Text by Longest Dictionary Prefix with Single-Char Fallback
StringsAuto-graded · 21 test casesLast updated
Scan a string left to right, always consuming the longest dictionary word starting at the current position, or one character if none match; tests tries and prefix matching.
Longest-Prefix Segmenter
A text-cleaning stage needs to cut a raw string into pieces using a fixed dictionary of words. You are given:
words: a list of distinct, non-empty strings (the dictionary).s: the string to segment.
Segment s by scanning from left to right with the following rule, starting at index pos = 0:
- Look at all dictionary words that are a prefix of the suffix of
sbeginning atpos. - If at least one word matches, take the longest one, append it to the output, and move
posforward by its length. - If no word matches, append the single character
s[pos]to the output and moveposforward by 1. - Stop when
posreaches the end ofs.
Return the list of pieces in the order they were produced.
The procedure is strictly greedy: once the longest match at a position is chosen, it is never reconsidered, even if a shorter choice would let later parts of the string be covered by dictionary words. Do not try to find a "better" overall segmentation.
A single-character piece produced by the fallback rule is output as an ordinary one-character string, the same as a one-character dictionary word would be.
If s is empty, return an empty list.
Constraints
0 <= len(s) <= 10^61 <= len(words) <= 10^51 <= len(words[i]) <= 100- The total length of all words is at most
10^6 - All words are distinct
sand all words consist of printable ASCII characters; treat every character generically- Checking every dictionary word at every position will be too slow for the largest inputs
Examples
Example 1
Input: segment_by_longest_prefix(['low', 'lower', 'new', 'est', 'wid', 'er'], 'lowernewestwidget')
Output: ['lower', 'new', 'est', 'wid', 'g', 'e', 't']
Example 2
Input: segment_by_longest_prefix(['ab', 'abc', 'cd'], 'abcd')
Output: ['abc', 'd']
Example 3
Input: segment_by_longest_prefix(['hello'], '')
Output: []
Hints
Hint 1
For a given start position you need the longest dictionary word that is a prefix of the remaining text. Think about a structure that shares common prefixes between words.
Hint 2
Build a trie of the words. From a start index, walk down the trie following the text, and remember the end index of the most recent node that completes a word.
Hint 3
After the walk stops, resume scanning from the end of the best complete word, not from where the walk stopped. If no complete word was seen, emit one character and advance by 1. Avoid slicing the string inside the loop.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
At each position we need the longest dictionary word that is a prefix of the remaining text. Comparing against every word at every position is far too slow, so we build a trie from the dictionary.
For a start index i, walk down the trie following s[i], s[i+1], and so on. Each time the current node completes a dictionary word, record that word and the index where it ends. The walk stops when the trie has no child for the next character or when the text ends. The last recorded word is the longest match.
- If a word was recorded, output it and set
ito its end index. - Otherwise output
s[i]and advance by one.
Why it is correct
- Every dictionary word that is a prefix of the suffix at
ilies on the path the walk follows, so each such word's end node is visited. - Nodes are visited in increasing depth, so the last completed word seen is the longest match.
- The walk may go past the last completed word (for example words
["a", "abcd"]and text"abcx"walk througha,b,c). We resume at the end of the recorded word, not where the walk stopped, so the skipped characters are processed normally from their own positions. - Each iteration advances
iby at least 1, because words are non-empty and the fallback moves by 1, so the loop terminates. - No backtracking happens, which matches the required greedy behavior (for
["ab","abc","cd"]and"abcd"the result is["abc","d"]). - An object sentinel marks word ends so it can never clash with a real character.
Complexity
Let n = len(s), S the total length of all words, and L the maximum word length.
- Time:
O(S + n * L). Building the trie costsO(S), and each start position walks at mostLsteps withO(1)dictionary lookups. - Space:
O(S + n)for the trie and the output.
Reference solution
from typing import List
def segment_by_longest_prefix(words: List[str], s: str) -> List[str]:
trie = {}
end_marker = object()
for word in words:
node = trie
for ch in word:
node = node.setdefault(ch, {})
node[end_marker] = word
pieces = []
i = 0
n = len(s)
while i < n:
node = trie
best_word = None
best_end = i
j = i
while j < n and s[j] in node:
node = node[s[j]]
j += 1
if end_marker in node:
best_word = node[end_marker]
best_end = j
if best_word is None:
pieces.append(s[i])
i += 1
else:
pieces.append(best_word)
i = best_end
return pieces