Word Break II (LeetCode 140): Solution and Explanation
Given a string with no spaces and a dictionary of words, insert spaces so that every piece is a dictionary word. Return every possible resulting sentence, in any order, reusing dictionary words as often as you like.
Watch it run step by step
Try your own input and write the code →Intuition
The first version of this problem only asks whether a split exists, and a boolean DP answers that. Here you need the actual sentences, so the natural tool is backtracking: from a starting index, try every prefix that is a dictionary word, recursively split the rest of the string, and attach the prefix to each of the rest's sentences.
Plain backtracking repeats work. In a string like "catsanddog", the suffix starting at index 7 ("dog") is reached through both "cat sand" and "cats and", and every time it is reached, the recursion rebuilds the same list of sentences. For longer strings with many overlapping splits, that repetition grows exponentially.
Memoizing on the start index fixes the repetition. backtrack(start) returns the list of all sentences that split s[start:], and the first computation is stored in memo. The base case is the end of the string, which returns a list holding one empty sentence, so a final word can be appended cleanly. A suffix with no valid split returns an empty list, so dead ends are discovered once and never explored again. The output itself can still be exponential, since some inputs have exponentially many valid sentences, but no suffix is solved twice.
Approach: Memoized backtracking on suffixes
- Convert
wordDictto a set for O(1) membership checks and create an emptymemodictionary. backtrack(start)returns the cached list ifstartis inmemo.- If
start == len(s), return[''], one empty sentence that marks a complete split. - Otherwise, for each
endfromstart + 1tolen(s), takeword = s[start:end]; if it is in the set, combine it with every sentence frombacktrack(end), adding a space only when that sentence is non-empty. - Store the collected list in
memo[start]and return it. - Return
backtrack(0).
Step-by-step example
s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
backtrack(0)finds"cat"(ending at 3) and callsbacktrack(3).- From index 3,
"sand"is a word, so it callsbacktrack(7). From 7,"dog"reaches the end, which returns[''], sobacktrack(7)is["dog"]and is memoized. - So
backtrack(3)is["sand dog"], giving"cat sand dog"at index 0. - Back at index 0,
"cats"(ending at 4) callsbacktrack(4)."and"leads tobacktrack(7), which is answered from the memo as["dog"], sobacktrack(4)is["and dog"]. - The final result is
["cat sand dog", "cats and dog"].
Code: Python, Java, C++
1class Solution:
2 def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
3 wordSet = set(wordDict)
4 memo = {}
5
6 def backtrack(start):
7 if start in memo:
8 return memo[start]
9 if start == len(s):
10 return ['']
11
12 result = []
13 for end in range(start + 1, len(s) + 1):
14 word = s[start:end]
15 if word in wordSet:
16 for sentence in backtrack(end):
17 if sentence:
18 result.append(word + ' ' + sentence)
19 else:
20 result.append(word)
21
22 memo[start] = result
23 return result
24
25 return backtrack(0)1class Solution {
2 private Set<String> wordSet;
3 private Map<Integer, List<String>> memo;
4
5 public List<String> wordBreak(String s, List<String> wordDict) {
6 wordSet = new HashSet<>(wordDict);
7 memo = new HashMap<>();
8 return backtrack(s, 0);
9 }
10
11 private List<String> backtrack(String s, int start) {
12 if (memo.containsKey(start)) return memo.get(start);
13
14 List<String> result = new ArrayList<>();
15 if (start == s.length()) {
16 result.add("");
17 return result;
18 }
19
20 for (int end = start + 1; end <= s.length(); end++) {
21 String word = s.substring(start, end);
22 if (wordSet.contains(word)) {
23 for (String sentence : backtrack(s, end)) {
24 if (sentence.isEmpty()) {
25 result.add(word);
26 } else {
27 result.add(word + " " + sentence);
28 }
29 }
30 }
31 }
32
33 memo.put(start, result);
34 return result;
35 }
36}1class Solution {
2public:
3 unordered_set<string> wordSet;
4 unordered_map<int, vector<string>> memo;
5
6 vector<string> wordBreak(string s, vector<string>& wordDict) {
7 wordSet = unordered_set<string>(wordDict.begin(), wordDict.end());
8 return backtrack(s, 0);
9 }
10
11 vector<string> backtrack(const string& s, int start) {
12 if (memo.count(start)) return memo[start];
13
14 vector<string> result;
15 if (start == s.size()) {
16 result.push_back("");
17 return result;
18 }
19
20 for (int end = start + 1; end <= s.size(); end++) {
21 string word = s.substr(start, end - start);
22 if (wordSet.count(word)) {
23 for (const string& sentence : backtrack(s, end)) {
24 if (sentence.empty()) {
25 result.push_back(word);
26 } else {
27 result.push_back(word + " " + sentence);
28 }
29 }
30 }
31 }
32
33 memo[start] = result;
34 return result;
35 }
36};Time and space complexity
O(n³ + output size)
There are n start indices. Each one tries n end positions and slices a substring of up to n characters, so the search itself is O(n³). Building sentences adds time proportional to the total output, which can be exponential, roughly O(2ⁿ × n) in the worst case.
O(n × output size)
The memo stores, for every start index, the list of sentences for that suffix, and the recursion stack is at most n deep.
Other approaches
Plain backtracking (time O(2ⁿ × n), space O(n))
The same recursion without a memo. It is fine when the answer set is small, but repeats the work for shared suffixes and can be exponential even when the answer is empty.
Boolean DP then backtracking (time O(n³ + output size), space O(n + output size))
First run the Word Break DP to mark which suffixes can be split at all, then backtrack only through positions marked true. This prunes dead ends early without storing full sentence lists.
Common mistakes
- Returning
[]instead of['']at the end of the string. With an empty list, no complete sentence can ever be built and the answer is always empty. - Always adding a space before the rest of the sentence, which leaves a trailing space after the last word.
- Checking membership against the list
wordDictinstead of a set, turning every lookup into a linear scan. - Memoizing on the substring instead of the index. It works but hashes long strings repeatedly; the start index uniquely identifies each suffix.
Frequently asked questions
What is the difference between Word Break and Word Break II?
Word Break asks whether any split exists and is solved with a boolean DP in polynomial time. Word Break II asks for every split, so it must enumerate sentences, and the output alone can be exponential.
Why does Word Break II need memoization?
Different prefixes often lead to the same remaining suffix. Caching the sentences for each start index means each suffix is split only once.
What is the time complexity of Word Break II?
The search is O(n³) with memoization, but generating the answer takes time proportional to the output, which is exponential in the worst case, for example on strings of repeated letters with words of many lengths.
Why does the base case return a list with an empty string?
It represents one valid way to split an empty suffix. That lets the last word of a sentence be added without a trailing space and signals a successful path.