Word Break II
Word Break II is LeetCode 140 (Hard). Given a string s and a list of words wordDict, add spaces to s to make sentences in which every word is in the dictionary, and return all such sentences in any order. A word may be reused.
shas at most 20 characters, and the total output is promised to stay under 10⁵ characters. Those limits are what make listing every sentence possible.- The yes/no version of this question is Word Break.
- 1 <= s.length <= 20
- 1 <= wordDict.length <= 1000
- 1 <= wordDict[i].length <= 10
- s and wordDict[i] consist of only lowercase English letters.
- All the strings of wordDict are unique.
- Input is generated in a way that the length of the answer doesn't exceed 10⁵.
Intuition
Every sentence starts with some word that is a prefix of s, followed by a sentence for the rest. So define build(start): the list of all sentences for the suffix that begins at start. Try each dictionary word that the suffix begins with, and glue it in front of every sentence that build returns for what is left.
Different first choices often lead to the same leftover suffix: cat + sand… and cats + and… both need the sentences for dog. So store the finished list for each start index and hand it out again on the next request.
When every solution must be listed and the choices split into a first piece plus a smaller copy of the same problem, use recursion that returns lists. Cache by the one index that describes the leftover input, since that index alone decides the answer.
Approach
Before reading on, split catsanddog with cat, cats, and, sand and dog by hand, and notice which suffix you solve twice. Then decide what build should return for the empty suffix.
Return one empty sentence at the end of the string
If start == len(s), return [""]. The empty suffix has exactly one split, using no words. Returning [] would mean "no split exists" and would wipe out every sentence built above it.
Reuse a list you already built
If start is in memo, return the stored list. The sentences for a suffix depend only on where it starts, not on how the earlier words were chosen.
Try each word the suffix begins with
For every end after start, take s[start:end] and keep it only if it is in the word set. Prefixes that are not words are dropped at once, so the recursion only follows real words.
Put the word in front of each rest-of-sentence
For each sentence rest from build(end), add word + " " + rest, or just word when rest is empty. That special case keeps a stray space off the end of every sentence.
Save the list, then return it
Store the list in memo[start] before returning, even when it is empty. The answer to the whole problem is build(0).
Code in Python, C++ and Java
Common pitfalls
Returning an empty list at the end of the string
if start == len(s):
return []if start == len(s):
return [""]The loop that adds a word in front of each rest-of-sentence then has nothing to loop over, so no sentence is ever produced. catsanddog returns [] instead of two sentences.
Caching only the suffixes that produced sentences
if out:
memo[start] = outmemo[start] = out # even when empty
Dead ends are then recomputed every time. For s = "aaaaaaaaaaaaaaaaaaab" with a, aa, aaa, nothing ever succeeds, nothing is cached, and the run explores every one of the exponentially many splits of the a's.
Complexity
Word Break II FAQ
Should I run the yes/no Word Break check first?
It helps when many inputs have no answer at all. A quick reachability pass rejects them in polynomial time, before any sentence lists are built. With the memo storing empty lists, the main search already avoids repeating dead ends, so the check is an optimisation, not a fix.
Is backtracking with a shared path list also accepted?
Yes. Push a word, recurse, and add the joined path to the answer when you reach the end, then pop. It writes each sentence only once, but without a memo it re-explores shared suffixes, so it relies on the small limit of 20 characters.