Word Break
Word Break is LeetCode 139 (Medium). Given a string s and a list of words wordDict, return true if s can be cut into pieces that are all dictionary words. A word may be used any number of times, and the pieces must cover the whole string with no gaps.
- The answer is only yes or no. Listing every possible split is a different, harder task.
shas at most 300 characters, so an approach that looks at each position once and tries every word there is fast enough.
- 1 <= s.length <= 300
- 1 <= wordDict.length <= 1000
- 1 <= wordDict[i].length <= 20
- s and wordDict[i] consist of only lowercase English letters.
- All the strings of wordDict are unique.
Intuition
Think of the gaps between characters as positions 0 to n. Position 0 is the start, position n is the end, and a dictionary word that fits at position i is a jump from i to i + len(word).
The question becomes: can a chain of jumps get from position 0 to position n? Mark position 0 as reached. Then go left to right, and from every reached position try each word; a word that fits marks where it ends as reached. Each position is handled once, so the shared middle parts of different splits are never recomputed.
A string cut into valid pieces, with only a yes/no answer, is a one-dimensional DP over prefix lengths. When every split must be listed, as in Word Break II, the same positions are kept but each one stores its sentences.
Approach
Before reading on, check cars with the words car, ca and rs by hand. Why does taking car first lead you astray, and what should you remember about positions instead?
Mark position 0 as reached
Make dp of size n + 1, all false, and set dp[0] = true. dp[i] means the first i characters can be split into words, and zero characters need no words at all.
Skip positions nothing reaches
Go through i = 0 … n − 1. If dp[i] is false, move on. No split of the string has a cut at i, so a word starting there can never be part of an answer.
From a reached position, try every word
For each word, check whether s continues with that word at index i. If it does, set dp[i + len(word)] = true: the prefix up to i splits into words, and one more word extends that split to the new position.
Read the answer at the end
Return dp[n]. It is true exactly when some chain of words starting at position 0 lands on the last position, which is a split of the whole string.
Code in Python, C++ and Java
Common pitfalls
Taking the first word that fits and never looking back
at each position, take one matching word and move on
mark every position each matching word reaches
For s = "cars" with car, ca and rs, taking car leaves s, which matches nothing, so the answer comes out false. The split ca + rs works, and only remembering both positions 3 and 2 finds it.
Making the table one slot too short
dp = [False] * n
dp = [False] * (n + 1)
A word that ends at the last character marks position n, which needs slot n. For s = "a" with ["a"], the short table throws an index error instead of returning true.
Complexity
s, m the number of words and k the longest word. Each of the n positions tries all m words, and each try compares up to k characters. Apart from the dictionary, only the n + 1 flags are stored.Word Break FAQ
Why is plain recursion too slow when it gives the same answers?
Recursion that tries each word and recurses on the rest asks about the same leftover suffix again and again. For a string of 30 as ending in b, with words a, aa and aaa, the number of calls grows exponentially before every one of them fails. Caching the answer per start index fixes it, and that cache is this table read right to left.
Can a trie make it faster?
Yes, when the dictionary is large. Walk a trie of the words from position i along s; every word end you pass marks a reachable position. That checks all words starting at i in one walk of at most k characters, giving O(n · k) time after the trie is built.