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.
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
Match cats at start 0"catsandog" starts with "cats" at 0, so add ending boundary 0+4=4.
visited0, 4
start=0reachable0|0c1a2t3reachables4a5n6d7o8g9
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,4}wordcatschecktext[0:4] = "cats"transitionadd 4
reachable
not shown→4
reachable
{0}→{0,4}
word
not shown→cats
Reject dog and sand at start 0Neither "dog" nor "sand" matches the prefix beginning at 0; reachable stays {0,4}.
visited0, 4
start=0reachable0|0c1a2t3reachables4a5n6d7o8g9
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,4}wordsdog, sandchecks"cat" != "dog"; "cats" != "sand"transitionno change
words
not shown→dog, sand
checks
not shown→"cat" != "dog"; "cats" != "sand"
transition
add 4→no change
Reject and, then match cat"and" misses at 0, but "cat" matches text[0:3], so add boundary 3.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4}branch1 not reachable: continue
start
0→1
branch
not shown→1 not reachable: continue
words
and, cat→not shown
Skip boundary 2Start 2 is not reachable, so no dictionary checks run.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4}branch2 not reachable: continue
start
1→2
branch
1 not reachable: continue→2 not reachable: continue
Reach 7 from boundary 3At reachable start 3, cats and dog miss; "sand" matches text[3:7], so add 3+4=7.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}checkscats miss; dog miss; sand matchestransitionadd 7
start
2→3
reachable
not shown→7
reachable
{0,3,4}→{0,3,4,7}
Finish checks at boundary 3Words "and" and "cat" also miss at start 3, so reachable remains {0,3,4,7}.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}checkscats miss; dog miss; sand miss; and matchestransitionadd 7 (already present)
start
3→4
checks
and miss; cat miss→cats miss; dog miss; sand miss; and matches
transition
no change→add 7 (already present)
Finish checks at boundary 4"cat" misses at start 4, so no new boundary is added.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}checkcat misstransitionno change
check
not shown→cat miss
transition
add 7 (already present)→no change
checks
cats miss; dog miss; sand miss; and matches→not shown
Skip boundaries 5 and 6Starts 5 and 6 are absent from reachable, so both iterations continue immediately.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}branches5 not reachable; 6 not reachable
start
4→6
branches
not shown→5 not reachable; 6 not reachable
check
cat miss→not shown
Fail every word at boundary 7Start 7 is reachable, but suffix "og" begins with none of cats, dog, sand, and, or cat.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}checkscats miss; dog miss; sand miss; and miss; cat misstransitionno change
start
6→7
checks
not shown→cats miss; dog miss; sand miss; and miss; cat miss
transition
not shown→no change
Skip boundaries 8 and 9Neither 8 nor 9 is reachable, so the scan ends with reachable={0,3,4,7}.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}branches8 not reachable; 9 not reachable
start
7→9
branches
not shown→8 not reachable; 9 not reachable
checks
cats miss; dog miss; sand miss; and miss; cat miss→not shown
Reject the full segmentationlen(text)=9 is not in reachable, so "catsandog" cannot be split entirely into dictionary words.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}comparison9 not in {0,3,4,7}resultfalse
comparison
not shown→9 not in {0,3,4,7}
result
not shown→false
branches
8 not reachable; 9 not reachable→not shown
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?
Sources and provenance
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 start
Matching word
New ending boundary
0
cats
4
0
cat
3
3
sand
7
4
and
7 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
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
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.
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
Match cats at start 0"catsandog" starts with "cats" at 0, so add ending boundary 0+4=4.
visited0, 4
start=0reachable0|0c1a2t3reachables4a5n6d7o8g9
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,4}wordcatschecktext[0:4] = "cats"transitionadd 4
reachable
not shown→4
reachable
{0}→{0,4}
word
not shown→cats
Reject dog and sand at start 0Neither "dog" nor "sand" matches the prefix beginning at 0; reachable stays {0,4}.
visited0, 4
start=0reachable0|0c1a2t3reachables4a5n6d7o8g9
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,4}wordsdog, sandchecks"cat" != "dog"; "cats" != "sand"transitionno change
words
not shown→dog, sand
checks
not shown→"cat" != "dog"; "cats" != "sand"
transition
add 4→no change
Reject and, then match cat"and" misses at 0, but "cat" matches text[0:3], so add boundary 3.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4}branch1 not reachable: continue
start
0→1
branch
not shown→1 not reachable: continue
words
and, cat→not shown
Skip boundary 2Start 2 is not reachable, so no dictionary checks run.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4}branch2 not reachable: continue
start
1→2
branch
1 not reachable: continue→2 not reachable: continue
Reach 7 from boundary 3At reachable start 3, cats and dog miss; "sand" matches text[3:7], so add 3+4=7.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}checkscats miss; dog miss; sand matchestransitionadd 7
start
2→3
reachable
not shown→7
reachable
{0,3,4}→{0,3,4,7}
Finish checks at boundary 3Words "and" and "cat" also miss at start 3, so reachable remains {0,3,4,7}.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}checkscats miss; dog miss; sand miss; and matchestransitionadd 7 (already present)
start
3→4
checks
and miss; cat miss→cats miss; dog miss; sand miss; and matches
transition
no change→add 7 (already present)
Finish checks at boundary 4"cat" misses at start 4, so no new boundary is added.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}checkcat misstransitionno change
check
not shown→cat miss
transition
add 7 (already present)→no change
checks
cats miss; dog miss; sand miss; and matches→not shown
Skip boundaries 5 and 6Starts 5 and 6 are absent from reachable, so both iterations continue immediately.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}branches5 not reachable; 6 not reachable
start
4→6
branches
not shown→5 not reachable; 6 not reachable
check
cat miss→not shown
Fail every word at boundary 7Start 7 is reachable, but suffix "og" begins with none of cats, dog, sand, and, or cat.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}checkscats miss; dog miss; sand miss; and miss; cat misstransitionno change
start
6→7
checks
not shown→cats miss; dog miss; sand miss; and miss; cat miss
transition
not shown→no change
Skip boundaries 8 and 9Neither 8 nor 9 is reachable, so the scan ends with reachable={0,3,4,7}.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}branches8 not reachable; 9 not reachable
start
7→9
branches
not shown→8 not reachable; 9 not reachable
checks
cats miss; dog miss; sand miss; and miss; cat miss→not shown
Reject the full segmentationlen(text)=9 is not in reachable, so "catsandog" cannot be split entirely into dictionary words.
exampletext = "catsandog", words = ["cats", "dog", "sand", "and", "cat"]positionMeaningboundary after index characters; cell 0 is empty prefixreachable{0,3,4,7}comparison9 not in {0,3,4,7}resultfalse
comparison
not shown→9 not in {0,3,4,7}
result
not shown→false
branches
8 not reachable; 9 not reachable→not shown
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 n characters and m entries, the reference performs at most (n+1)m prefix tests.
Each costs O(k+1) for maximum token length k; scanning and reachable storage cost O(n+1).
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.