Word Break II solution explained
Word Break II asks for every way to split a string into a sequence of dictionary words, returned as space-separated sentences. Solve it with backtracking from each start index: try every dictionary word that matches at that position and recurse on the rest. Memoize the list of sentences for each start index, or precompute which suffixes can be split at all, so dead ends are explored once. The output itself can grow exponentially with the string length, so no algorithm is polynomial in the worst case; the goal is to avoid repeating work on top of the output.
By Evin JohnPublished 8 min read
The problem in our own words
You are given a string s with no spaces and a list of dictionary words. Insert spaces into s so that every resulting piece is a word from the list, and return every distinct sentence you can make this way, in any order. A word can be used any number of times. If no split works, return an empty list.
| s | Words | Sentences |
|---|---|---|
| sunflowerbed | sun, flower, sunflower, bed, flowerbed, owe, rbed | sun flower bed / sun flowerbed / sunflower bed |
| icecreamcone | ice, cream, icecream, cone, creamcone, am, cre | ice cre am cone / ice cream cone / ice creamcone / icecream cone |
| treehouse | tree, house, hou | tree house |
| a | (empty list) | none |
Words like owe and rbed match somewhere inside sunflowerbed, but no complete split uses them, so they never appear in an answer. That is the dead-end situation the optimizations below are about.
What the interviewer wants
Word Break II usually follows the yes-or-no version of the question (can s be split at all?), which is a classic dynamic programming problem. Here you must list the splits, so DP alone is not enough; you need search. The interviewer is looking for backtracking with memoization, an honest complexity answer that mentions output size, and a defence against inputs like a long run of the same letter followed by a letter no word contains, where naive search explodes without producing anything.
Plain backtracking
Put the words in a set. Starting at index 0, try every end position; if the piece from start to end is a word, add it to the current sentence and recurse from end. When the start reaches the end of the string, record the sentence. Undo the choice and try the next end. This is correct and short, and it is the right first version to say out loud.
def word_break_all_plain(s, words):
vocab = set(words)
out = []
def go(start, picked):
if start == len(s):
out.append(" ".join(picked))
return
for end in range(start + 1, len(s) + 1):
piece = s[start:end]
if piece in vocab:
picked.append(piece)
go(end, picked)
picked.pop()
go(0, [])
return outIts weakness is repeated work. Given many a's followed by a b, with the words a, aa and aaa, the search reaches the same suffix by many different routes and fails on the b each time, without ever producing a sentence. The number of routes grows exponentially with the run of a's.
Memoize by start index
Every way of finishing the string from index i is independent of how you got to i. So compute tails(i), the list of completions from i, once and reuse it. tails(i) is built by taking each word that matches at i and prefixing it to every completion in tails of the word's end. The empty suffix has exactly one completion, the empty sentence, and a suffix with no valid split gets an empty list, which is also remembered.
def word_break_all(s, words):
vocab = set(words)
longest = max((len(w) for w in vocab), default=0)
memo = {len(s): [""]} # the empty tail has one (empty) completion
def tails(start):
if start in memo:
return memo[start]
found = []
for end in range(start + 1, min(len(s), start + longest) + 1):
piece = s[start:end]
if piece in vocab:
for rest in tails(end):
found.append(piece + (" " + rest if rest else ""))
memo[start] = found # an empty list also records "dead end"
return found
return tails(0)Limiting end positions to the longest word length saves time when the dictionary is made of short words and s is long. On the dead-end input, each index now fails once instead of once per route, so the search does polynomial work and returns an empty list quickly. When there are many answers, the memo still has to store them, and the total size of the output is what dominates.
Prune with a feasibility table
An alternative keeps the simple backtracking but first fills a boolean table: ok[i] is true when the suffix starting at i can be split at all. That is the yes-or-no Word Break DP, run from the right end. During backtracking, only step to an end position whose suffix is splittable. Every branch the search takes then leads to at least one sentence, so no time is wasted on dead ends.
function wordBreakAll(s, words) {
const vocab = new Set(words);
const n = s.length;
// ok[i] is true when s.slice(i) can be split at all; skip dead ends early
const ok = new Array(n + 1).fill(false);
ok[n] = true;
for (let i = n - 1; i >= 0; i--) {
for (let j = i + 1; j <= n && !ok[i]; j++) {
if (ok[j] && vocab.has(s.slice(i, j))) ok[i] = true;
}
}
const out = [];
const picked = [];
const go = (start) => {
if (start === n) {
out.push(picked.join(" "));
return;
}
for (let end = start + 1; end <= n; end++) {
if (!ok[end]) continue;
const piece = s.slice(start, end);
if (!vocab.has(piece)) continue;
picked.push(piece);
go(end);
picked.pop();
}
};
if (ok[0]) go(0);
return out;
}This version builds sentences only at the end of a successful branch, which uses less memory than storing every completion for every index. Both approaches return the same set of sentences; the memo version is often quicker when many partial completions are shared.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Plain backtracking | Exponential, even when the answer is empty | O(n) recursion depth |
| Memo by start index | O(n · L) lookups plus O(S) to build the answers, plus the shared completion lists | Can be large: every index stores its completions |
| Feasibility table plus backtracking | O(n²) for the table, then roughly proportional to S | O(n) plus the output |
The output can be enormous. A string of twenty a's with the words a, aa and aaa has 121,415 valid sentences. No algorithm can list them faster than it takes to write them, which is why interviewers accept output-sensitive bounds here.
Edge cases
- An empty dictionary: no sentences.
- A string that can be split in exactly one way.
- Words that are prefixes of other words, such as sun and sunflower.
- A long run of one letter ending in a letter no word contains: the classic dead-end input.
- Repeated words in the dictionary list: the set removes them, so no duplicate sentences.
Mistakes
- Using the yes-or-no DP and trying to reconstruct a single path, when every path is required.
- Searching the word list linearly at each step instead of using a set.
- Not remembering failures, so dead-end suffixes are re-explored.
- Adding a trailing or leading space when joining pieces.
- Recursing in Python on very long inputs; the memo version is fine for interview sizes but say where its depth limit is.
- Claiming polynomial time without mentioning output size.
How to explain it out loud
Fictional example
- Candidate
- I need every split, so this is a search: at each index I try each word that matches there and recurse on the rest.
- Candidate
- How I reach an index doesn't change how the rest can be split, so I'll memoize the list of completions per start index. Failed suffixes get an empty list, which stops repeated dead ends.
- Interviewer
- What's the time complexity?
- Candidate
- It depends on the output. The number of sentences can be exponential, for example a string of a's with words a and aa. Beyond the output, the work per index is bounded by the longest word length times the string length.
Related problems
Backtracking that builds every answer is also the core of Subsets and Permutations. Memoized search on a grid appears in Longest Increasing Path in a Matrix, and the cost reasoning about output size is covered in the Big O cheat sheet. Range Sum Query is a change of pace: a design question about repeated queries.
Preparing with Natively
Word Break II is a good problem for checking whether your memo really prevents repeated work. Natively can read it from a screenshot on Mac or Windows and present an approach and code in its overlay, so you can compare where the dead-end check sits in each version. In a spoken practice round, it writes down what you said, which helps you review how you described the output-sensitive cost. More on the AI interview assistant.
Questions people ask
How do you solve Word Break II?
Backtrack from each start index, trying every dictionary word that matches there and recursing on the rest. Memoize the list of completions for each start index so each suffix is solved once.
What is the time complexity of Word Break II?
It depends on the output, which can be exponential in the string length. Beyond writing the answers, memoization keeps the work per index bounded by the string length times the longest word.
How do you avoid dead ends in Word Break II?
First compute which suffixes can be split at all, using the yes-or-no Word Break DP from the right end, then only step to positions whose suffix is splittable.
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. Word Break II asks for every split, which needs search on top of that.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
