KatInterview

Split Text by Longest Dictionary Prefix with Single-Char Fallback

StringsAuto-graded · 21 test cases
MediumAuto-gradedStringstriegreedystring-processing

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

  1. Look at all dictionary words that are a prefix of the suffix of s beginning at pos.
  2. If at least one word matches, take the longest one, append it to the output, and move pos forward by its length.
  3. If no word matches, append the single character s[pos] to the output and move pos forward by 1.
  4. Stop when pos reaches the end of s.

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^6
  • 1 <= len(words) <= 10^5
  • 1 <= len(words[i]) <= 100
  • The total length of all words is at most 10^6
  • All words are distinct
  • s and 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.