Word Break II (LeetCode 140): Solution and Explanation

Hard
Array
Hash Table
String
Dynamic Programming
Backtracking
Trie
Memoization

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Convert wordDict to a set for O(1) membership checks and create an empty memo dictionary.
  2. backtrack(start) returns the cached list if start is in memo.
  3. If start == len(s), return [''], one empty sentence that marks a complete split.
  4. Otherwise, for each end from start + 1 to len(s), take word = s[start:end]; if it is in the set, combine it with every sentence from backtrack(end), adding a space only when that sentence is non-empty.
  5. Store the collected list in memo[start] and return it.
  6. Return backtrack(0).

Step-by-step example

s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
  1. backtrack(0) finds "cat" (ending at 3) and calls backtrack(3).
  2. From index 3, "sand" is a word, so it calls backtrack(7). From 7, "dog" reaches the end, which returns [''], so backtrack(7) is ["dog"] and is memoized.
  3. So backtrack(3) is ["sand dog"], giving "cat sand dog" at index 0.
  4. Back at index 0, "cats" (ending at 4) calls backtrack(4). "and" leads to backtrack(7), which is answered from the memo as ["dog"], so backtrack(4) is ["and dog"].
  5. 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)

Time and space complexity

Time

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.

Space

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 wordDict instead 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.