Skip to content
mlmentorship

Launch words only from completely segmentable prefixes

Treat text boundaries as reachable states, reject partial coverage, then reconstruct one segmentation or count distinct parses.

Published · 29 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Launch words only from completely segmentable prefixes

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A Python string text and a list words of dictionary strings. Output. Return True if dictionary words can concatenate to exactly text; otherwise return False. Rules. Words may be reused, but characters cannot be skipped, reordered, or shared between consecutive tokens. Match exact code points without normalization or fuzzy matching. Duplicate dictionary entries add no new feasibility. Return existence, not the number of parses. Preserve inputs; empty text returns True. Example. "leetcode" with ["leet", "code"] returns True, using "leet" + "code". For "catsandog" with ["cats", "dog", "sand", "and", "cat"], return False.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Only reachable boundaries may launch dictionary words; each full prefix match adds its ending boundary.

Problem trace

Every word must connect to a segmentation already reachable from boundary zero

Input and goalCheck whether a string can be split into dictionary words.
Initialize boundary 0The empty prefix is reachable, so reachable={0} before scanning any start.
03479
visited0
start=0reachable0|0c1a2t3s4a5n6d7o8g9
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0}operationinitialize
start
0
reachable
0
position meaning
boundary after index characters; cell 0 is empty prefix

Recognize it
The string must be segmented into reusable dictionary words, so each valid prefix endpoint can seed another exact prefix match.
Keep true
Before scanning start s, reachable contains exactly the boundaries proven segmentable using dictionary words from earlier starts; only members may create new endpoints.
Reuse it
Treat partial solutions as reachable boundaries and propagate only from proven states; this transfers to sentence segmentation, path reachability, and parsing with reusable tokens.
The empty prefix is reachable, so reachable={0} before scanning any start. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does finding dog inside catsandog not establish a complete segmentation from boundary zero to nine?
Full interview answer 29 min read

Determine whether an entire string can be split into consecutive words from a supplied dictionary.

Problem

Input. A Python string text and a list words of dictionary strings.

Output. Return True if dictionary words can concatenate to exactly text; otherwise return False.

Rules. Words may be reused, but characters cannot be skipped, reordered, or shared between consecutive tokens. Match exact code points without normalization or fuzzy matching. Duplicate dictionary entries add no new feasibility. Return existence, not the number of parses. Preserve inputs; empty text returns True.

Example. "leetcode" with ["leet", "code"] returns True, using "leet" + "code". For "catsandog" with ["cats", "dog", "sand", "and", "cat"], return False.

Picture

Boundary 0 sits before the first character; boundary 9 sits after the last. Seed 0 because the empty prefix needs no words. At a reachable start, an exact word match proves its ending boundary reachable. Positive-length words point forward, so increasing start order processes each dependency before its consumer.

Proven startMatching wordNew ending boundary
0cats4
0cat3
3sand7
4and7 again

Boundary 7 leaves suffix og, not dog. The final set is {0,3,4,7}, so boundary 9 remains unreachable. Changing the text to catsanddog permits cats + and + dog. Repeated discoveries collapse because the state asks existence, not multiplicity.

Problem trace

Separate cars dictionary: a shorter reachable cut can enable the full suffix

Worked example: a tempting longest prefix can leave an impossible suffixFor cars and dictionary (car,ca,rs), greedy car leaves invalid s. The valid split is ca plus rs; reachability must consider both boundaries.A longer reachable prefix can leavean impossible suffixDictionary: car, ca, rscar then s: suffix absentcarsca then rs: both words existcarsReachable boundaries, not the longestgreedy word, establish the fullsplit.
Read it this way: For cars and dictionary (car,ca,rs), greedy car leaves invalid s. The valid split is ca plus rs; reachability must consider both boundaries. Which suffix becomes reachable when the first cut moves from position three to position two?
Reference drawing

Problem trace

Every word must connect to a segmentation already reachable from boundary zero

Worked example: a tempting longest prefix can leave an impossible suffixFor cars and dictionary (car,ca,rs), greedy car leaves invalid s. The valid split is ca plus rs; reachability must consider both boundaries.A longer reachable prefix can leavean impossible suffixDictionary: car, ca, rscar then s: suffix absentcarsca then rs: both words existcarsReachable boundaries, not the longestgreedy word, establish the fullsplit.
Execution trace
Input and goalCheck whether a string can be split into dictionary words.
Initialize boundary 0The empty prefix is reachable, so reachable={0} before scanning any start.
03479
visited0
start=0reachable0|0c1a2t3s4a5n6d7o8g9
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0}operationinitialize
start
0
reachable
0
position meaning
boundary after index characters; cell 0 is empty prefix

Recognize it
The string must be segmented into reusable dictionary words, so each valid prefix endpoint can seed another exact prefix match.
Keep true
Before scanning start s, reachable contains exactly the boundaries proven segmentable using dictionary words from earlier starts; only members may create new endpoints.
Reuse it
Treat partial solutions as reachable boundaries and propagate only from proven states; this transfers to sentence segmentation, path reachability, and parsing with reusable tokens.
The empty prefix is reachable, so reachable={0} before scanning any start. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does finding dog inside catsandog not establish a complete segmentation from boundary zero to nine?
Read it this way: For cars and dictionary (car,ca,rs), greedy car leaves invalid s. The valid split is ca plus rs; reachability must consider both boundaries. Which suffix becomes reachable when the first cut moves from position three to position two?

Code

def word_break(text: str, words: list[str]) -> bool:
   reachable = {0}
   for start in range(len(text) + 1):
      if start not in reachable:
         continue
      for word in words:
         if text.startswith(word, start):
            reachable.add(start + len(word))
   return len(text) in reachable

Empty text succeeds even with no tokens. Empty tokens add self-loops but do not change Boolean reachability. Duplicate dictionary entries repeat work without changing the answer.

With characters and entries, the reference performs at most prefix tests. Each costs for maximum token length ; scanning and reachable storage cost .

Failure Check

An occurrence of dog cannot launch from an unreachable start. Greedily taking the longest match can also miss a complete alternative parse.

Change to One Segmentation Witness

New task: Return words covering the text, or None if impossible.

Picture and change: Save a parent boundary and word on first discovery, then follow parents backward and reverse.

def word_break_witness(text, words):
   parent = {0: None}
   for start in range(len(text) + 1):
      if start not in parent:
         continue
      for word in words:
         end = start + len(word)
         if word and end not in parent and text.startswith(word, start):
            parent[end] = start, word
   if len(text) not in parent:
      return None
   answer, end = [], len(text)
   while end:
      end, word = parent[end]
      answer.append(word)
   return answer[::-1]

Check: "leetcode" and ["leet","code"] return ["leet","code"]; "x" with ["a"] returns None. Empty text returns []. Every selected token is nonempty, so parent boundaries strictly decrease during reconstruction. First discovery does not promise the fewest words.

Use when: A Boolean answer needs inspectable evidence.

Change to Parse Counts

New task: Count distinct token sequences, treating duplicate dictionary strings as the same token.

Picture and change: Seed one empty parse, then add every matching predecessor’s count instead of collapsing endpoints.

def segmentation_count(text, words):
   tokens = sorted(set(words) - {""})
   counts = [0] * (len(text) + 1)
   counts[0] = 1
   for start in range(len(text)):
      for word in tokens:
         if text.startswith(word, start):
            counts[start + len(word)] += counts[start]
   return counts[-1]

Check: "aaa" with ["a","aa","a"] has three parses: ["a","a","a"], ["a","aa"] and ["aa","a"]. Empty text has one empty parse. The helper removes empty tokens and deduplicates and sorts the rest. Integer additions may become more expensive as parse counts grow.

Use when: Multiplicity, rather than existence or one witness, is required.

Transfer Check

What happens if counting permits arbitrarily many empty tokens?

Answer

Any existing parse can receive unlimited empty tokens, creating infinitely many token sequences. Exclude them or explicitly bound token count.