LeetCode #140 Hard

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.

  • s has 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.
Constraints
  • 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⁵.
stringbacktrackingmemoization
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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).

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
▶3 words = set(wordDict)
▶4 memo = {}
▶5 
▶6 def build(start):
▶7 if start == len(s):
▶8 return [""]
▶9 if start in memo:
▶10 return memo[start]
▶11 out = []
▶12 for end in range(start + 1, len(s) + 1):
▶13 word = s[start:end]
▶14 if word in words:
▶15 for rest in build(end):
▶16 out.append(word + " " + rest if rest else word)
▶17 memo[start] = out
▶18 return out
▶19 
▶20 return build(0)
catsanddogcallsmemo: finished listsfrom 0: try 'cat'nothing finished yet'cat' is a word → split the rest from 3
start0
word'cat'
Of the prefixes starting at 0, 'cat' is in the dictionary (prefixes that are not words are passed over). Every sentence that starts with it needs a sentence for the letters from 3 on, so recurse there.
catsanddogcallsmemo: finished listsfrom 0: try 'cat'from 3: try 'sand'nothing finished yet'sand' is a word → split the rest from 7
start3
word'sand'
Of the prefixes starting at 3, 'sand' is in the dictionary (prefixes that are not words are passed over). Every sentence that starts with it needs a sentence for the letters from 7 on, so recurse there.
catsanddogcallsmemo: finished listsfrom 0: try 'cat'from 3: try 'sand'from 7: try 'dog'nothing finished yet'dog' is a word → split the rest from 10
start7
word'dog'
Of the prefixes starting at 7, 'dog' is in the dictionary (prefixes that are not words are passed over). Every sentence that starts with it needs a sentence for the letters from 10 on, so recurse there.
catsanddogcallsmemo: finished listsfrom 0: try 'cat'from 3: try 'sand'from 7: try 'dog'nothing finished yetreached the end → one sentence with no words
start10
returnsone empty sentence
Nothing is left to split, and that counts as exactly one way: use no words. Returning one empty sentence lets the caller put its word in front.
catsanddogcallsmemo: finished listsfrom 0: try 'cat'from 3: try 'sand'from 7: try 'dog'nothing finished yetadd 'dog' in front → dog
start7
sentence'dog'
The rest is the empty sentence, so the sentence is just 'dog', with no trailing space.
catsanddogcallsmemo: finished listsfrom 0: try 'cat'from 3: try 'sand'from 7at 7dogsave 1 sentence for index 7
start7
memo1 sentence
Every word that starts at 7 has been tried. The finished list is stored for index 7, so any later path that reaches it gets the list at once.
catsanddogcallsmemo: finished listsfrom 0: try 'cat'from 3: try 'sand'at 7dogadd 'sand' in front → sand dog
start3
sentence'sand dog'
The rest of the string can be 'dog', so putting 'sand' in front gives a sentence for the suffix at 3.
catsanddogcallsmemo: finished listsfrom 0: try 'cat'from 3at 7dogat 3sand dogsave 1 sentence for index 3
start3
memo1 sentence
Every word that starts at 3 has been tried. The finished list is stored for index 3, so any later path that reaches it gets the list at once.
catsanddogcallsmemo: finished listsfrom 0: try 'cat'at 7dogat 3sand dogadd 'cat' in front → cat sand dog
start0
sentence'cat sand dog'
The rest of the string can be 'sand dog', so putting 'cat' in front gives a sentence for the suffix at 0.
catsanddogcallsmemo: finished listsfrom 0: try 'cats'at 7dogat 3sand dog'cats' is a word → split the rest from 4
start0
word'cats'
Of the prefixes starting at 0, 'cats' is in the dictionary (prefixes that are not words are passed over). Every sentence that starts with it needs a sentence for the letters from 4 on, so recurse there.
catsanddogcallsmemo: finished listsfrom 0: try 'cats'from 4: try 'and'at 7dogat 3sand dog'and' is a word → split the rest from 7
start4
word'and'
Of the prefixes starting at 4, 'and' is in the dictionary (prefixes that are not words are passed over). Every sentence that starts with it needs a sentence for the letters from 7 on, so recurse there.
catsanddogcallsmemo: finished listsfrom 0: try 'cats'from 4: try 'and'at 7dogat 3sand dogsentences from 7 already known → reuse
start7
memo1 sentence
A different choice of earlier words has already reached index 7. The sentences for this suffix do not depend on how we got here, so the stored list is returned without searching again.
catsanddogcallsmemo: finished listsfrom 0: try 'cats'from 4: try 'and'at 7dogat 3sand dogadd 'and' in front → and dog
start4
sentence'and dog'
The rest of the string can be 'dog', so putting 'and' in front gives a sentence for the suffix at 4.
catsanddogcallsmemo: finished listsfrom 0: try 'cats'from 4at 7dogat 3sand dogat 4and dogsave 1 sentence for index 4
start4
memo1 sentence
Every word that starts at 4 has been tried. The finished list is stored for index 4, so any later path that reaches it gets the list at once.
catsanddogcallsmemo: finished listsfrom 0: try 'cats'at 7dogat 3sand dogat 4and dogadd 'cats' in front → cats and dog
start0
sentence'cats and dog'
The rest of the string can be 'and dog', so putting 'cats' in front gives a sentence for the suffix at 0.
catsanddogcallsmemo: finished listsfrom 0at 7dogat 3sand dogat 4and dogat 0cat sand dogat 0cats and dogsave 2 sentences for index 0
start0
memo2 sentences
Every word that starts at 0 has been tried. The finished list is stored for index 0, so any later path that reaches it gets the list at once.
catsanddogcallsmemo: finished listsall calls returnedat 7dogat 3sand dogat 4and dogat 0cat sand dogat 0cats and dog2 sentences for the whole string → return them
result'cat sand dog', 'cats and dog'
The list stored for index 0 holds every way to split the whole string. Endings shared by several sentences were worked out only once.
05

Common pitfalls

Returning an empty list at the end of the string

✗ Wrong
if start == len(s):
    return []
✓ Right
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

✗ Wrong
if out:
    memo[start] = out
✓ Right
memo[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.

06

Complexity

Time
O(n · 2ⁿ) worst case
Space
O(n · 2ⁿ) worst case
A string of n equal letters with every short run in the dictionary has 2ⁿ⁻¹ sentences, and each takes up to n characters to write, so no method can beat the size of the output. The cache makes sure each start index is expanded only once, so the extra work beyond writing the sentences is O(n²) substring checks.
07

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.