Full answer
Problem
Given a string s and a list of words, return True if s can be segmented into one or more dictionary words (words may repeat). Follow-up: return all such segmentations as space-separated sentences.
Example: "leetcode" with ["leet", "code"] is True; "catsandog" with ["cats", "dog", "sand", "and", "cat"] is False; "catsanddog" has two sentences: "cat sand dog" and "cats and dog".
Constraints: 1 <= len(s) <= 300, up to 1,000 words of length up to 20.
Brute force
Try every word as a prefix and recurse on the rest. Without memoization a string like "aaaa...ab" with words "a", "aa", "aaa" causes exponential work, because the same suffix is retried along many paths.
Optimal approach
- Put words in a set; let L be the longest word length.
ok = [True] + [False] * n.- For i from 1 to n, for j from max(0, i - L) to i - 1: if
ok[j]ands[j:i]is in the set, setok[i] = Trueand stop scanning j. - Return
ok[n].
All sentences: memoize go(i) = list of sentences for s[i:], trying each end j where s[i:j] is a word.
Why it works
A valid split of the first i characters has a last word s[j:i], and the part before it must itself be a valid split, which is ok[j]. Checking all j covers every possible last word; words longer than L cannot match, so the restricted range loses nothing. Memoizing by start index in the listing version means each suffix's sentences are built once.
Complexity
Decision: O(n * L) set lookups, each hashing a substring of length up to L, so O(n * L^2) character work in the worst case; O(n) space. A trie walk from each start position avoids rebuilding substrings. Listing: output-sensitive and exponential in the worst case.
Code
import random
from functools import lru_cache
def word_break(s, words):
"""Can s be split into dictionary words? dp[i] = some j < i with dp[j] and s[j:i] in words.
Only look back as far as the longest word: O(n * L) substring checks."""
wordset = set(words)
if not wordset:
return s == ""
longest = max(map(len, wordset))
ok = [True] + [False] * len(s)
for i in range(1, len(s) + 1):
for j in range(max(0, i - longest), i):
if ok[j] and s[j:i] in wordset:
ok[i] = True
break
return ok[-1]
def word_break_all(s, words):
"""Every sentence (can be exponential in count); memoised by start index."""
wordset = set(words)
@lru_cache(maxsize=None)
def go(i):
if i == len(s):
return [""]
out = []
for j in range(i + 1, len(s) + 1):
if s[i:j] in wordset:
out += [s[i:j] + (" " + rest if rest else "") for rest in go(j)]
return out
return sorted(go(0))
def brute(s, words):
"""Try every prefix recursively, no memo: exponential."""
if s == "":
return True
return any(s.startswith(w) and brute(s[len(w):], words) for w in words if w)
if __name__ == "__main__":
assert word_break("leetcode", ["leet", "code"])
assert word_break("applepenapple", ["apple", "pen"])
assert not word_break("catsandog", ["cats", "dog", "sand", "and", "cat"])
assert word_break("", ["a"]) and not word_break("a", [])
assert word_break_all("catsanddog", ["cat", "cats", "and", "sand", "dog"]) == ["cat sand dog", "cats and dog"]
rng = random.Random(83)
for _ in range(1000):
words = list({"".join(rng.choice("ab") for _ in range(rng.randint(1, 3))) for _ in range(rng.randint(0, 4))})
s = "".join(rng.choice("ab") for _ in range(rng.randint(0, 10)))
assert word_break(s, words) == brute(s, words) == bool(word_break_all(s, words))
print("all tests passed")Save as b83_word_break.py and run python3 b83_word_break.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty string (True: zero words). Empty dictionary. A word that is a prefix of another (cat, cats). Repeated words. Very long strings with short words (L keeps the inner loop short).
Pattern
Prefix segmentation DP: "can prefix i be completed from some earlier valid point". Related: palindrome partitioning (minimum cuts), decode ways, concatenated words, and sentence segmentation for languages written without spaces.
import random
from functools import lru_cache
def word_break(s, words):
"""Can s be split into dictionary words? dp[i] = some j < i with dp[j] and s[j:i] in words.
Only look back as far as the longest word: O(n * L) substring checks."""
wordset = set(words)
if not wordset:
return s == ""
longest = max(map(len, wordset))
ok = [True] + [False] * len(s)
for i in range(1, len(s) + 1):
for j in range(max(0, i - longest), i):
if ok[j] and s[j:i] in wordset:
ok[i] = True
break
return ok[-1]
def word_break_all(s, words):
"""Every sentence (can be exponential in count); memoised by start index."""
wordset = set(words)
@lru_cache(maxsize=None)
def go(i):
if i == len(s):
return [""]
out = []
for j in range(i + 1, len(s) + 1):
if s[i:j] in wordset:
out += [s[i:j] + (" " + rest if rest else "") for rest in go(j)]
return out
return sorted(go(0))
def brute(s, words):
"""Try every prefix recursively, no memo: exponential."""
if s == "":
return True
return any(s.startswith(w) and brute(s[len(w):], words) for w in words if w)
if __name__ == "__main__":
assert word_break("leetcode", ["leet", "code"])
assert word_break("applepenapple", ["apple", "pen"])
assert not word_break("catsandog", ["cats", "dog", "sand", "and", "cat"])
assert word_break("", ["a"]) and not word_break("a", [])
assert word_break_all("catsanddog", ["cat", "cats", "and", "sand", "dog"]) == ["cat sand dog", "cats and dog"]
rng = random.Random(83)
for _ in range(1000):
words = list({"".join(rng.choice("ab") for _ in range(rng.randint(1, 3))) for _ in range(rng.randint(0, 4))})
s = "".join(rng.choice("ab") for _ in range(rng.randint(0, 10)))
assert word_break(s, words) == brute(s, words) == bool(word_break_all(s, words))
print("all tests passed")Boolean prefix DP bounded by the longest word and a memoized sentence lister, cross-checked against plain recursion on random strings and dictionaries.
Complexity
Time: O(n * L) lookups. Space: O(n). Each lookup hashes a substring of up to L characters; a trie avoids building substrings. Listing all sentences is output-sensitive.
By level
Fresher: Writes the boolean prefix table with a set of words and traces it on a short example. Explains why greedy longest match fails.
Mid: Bounds the inner loop by the longest word, writes the memoized sentence lister, and discusses output size. Uses a trie to avoid substring building.
Senior: Discusses segmentation for search queries and languages without spaces, ranking splits with word frequencies, and memory for large dictionaries. Evaluates trie versus hashing for lookup speed.
Key points
- ok[i] true if some ok[j] and s[j:i] is a word
- Limit j by the longest word
- Use a set (or trie) for lookups
- Memoize by start index for the listing version
- Listing output can be exponential
Common mistakes
- Greedy longest-match splitting
- Recursion without memoization
- Checking all j without the L bound on long strings
- Forgetting that words may repeat
Follow-ups
- How would you find the split with the fewest words?
- How would a trie speed this up?
- How would you handle a dictionary of millions of words?
Tips
- Show why greedy matching fails
- Explain the L bound
- Mention exponential output for the listing version
Evaluation rubric
- Correct DP
- Uses a set
- Correct complexity
- Handles the listing follow-up