Word Break solution explained
Word Break asks whether a string with no spaces can be cut into pieces that all appear in a given word list, with words allowed to repeat. The standard answer is dynamic programming over prefixes: mark each prefix length that can be fully split, and a prefix is splittable when some shorter splittable prefix is followed by a dictionary word. That runs in roughly O(n · L²) time, where L is the longest word, instead of the exponential cost of plain backtracking.
By Evin JohnPublished 8 min read
The problem, restated
Someone typed a message and the space bar broke. You have the text as one long run of letters and a vocabulary of allowed words. Decide whether the run can be split into a sequence of vocabulary words, using each word as often as you like. You only need a yes or no, not the split itself, although interviewers often ask for the split next.
| Text | Vocabulary | Answer | Why |
|---|---|---|---|
| carpets | car, carpet, pets | true | car + pets works; carpet first leaves a lone s |
| dogsled | dog, dogs, led, sled | true | dog + sled and dogs + led both work |
| sunflowerbed | sun, flow, flower, bed, erbed | true | sun + flow + erbed or sun + flower + bed |
| carpetx | car, pet, carpet | false | Nothing in the list covers the final x |
| aaaaab | a, aa, aaa | false | Many ways to eat the a's, none for the b |
| tiktik | tik | true | The same word is reused |
The first row shows why a greedy rule fails. Taking the longest match first picks carpet, and the leftover s matches nothing, while the shorter car would have led to a full split. Any correct method has to be willing to try more than one first piece.
What interviewers look for
This is one of the most common first dynamic programming questions because the recursion is easy to see and the waste in it is easy to show. A strong candidate writes the backtracking idea, spots that the same suffix gets solved again and again, and converts it into a table indexed by position. Interviewers also listen for the cost of slicing strings, which many people leave out of their complexity answer.
Follow-ups you should expect
- Return one valid split. Store, for each reachable position, the start of the last word that reached it, then walk back from the end.
- Return every valid split. That is usually called Word Break II. The output itself can be exponential, so memoize lists of sentences per suffix and say the cost depends on the output size.
- The vocabulary is huge. A trie lets you walk forward from each reachable position and stop as soon as no word continues, so you never build substrings that cannot match.
- What does the empty string return? With zero pieces needed, the usual convention is true. Confirm it out loud.
Brute force: try every first word
Pick a word that matches the start of the text, cut it off, and solve the rest the same way. If no first word leads to a full split, the answer is false. It is short and correct, and it is the right thing to say first.
def can_split_slow(s, words):
if s == "":
return True
for w in words:
if w and s.startswith(w) and can_split_slow(s[len(w):], words):
return True
return FalseFeed it thirty a's followed by a b, with the vocabulary a, aa and aaa. Every way of eating the a's reaches the b and fails, and the number of ways grows like a Fibonacci-style sequence. The function keeps asking the same question, can this suffix be split, for the same suffix. That repeated question is the signal for dynamic programming.
The optimal approach: a table of reachable prefixes
Flip the recursion around and work left to right. Let ok[i] mean the first i characters can be split into words. The empty prefix needs no words, so ok[0] is true. For each end position, look at every start position before it: if ok[start] is true and the slice from start to end is a vocabulary word, then ok[end] is true. The answer is ok[n]. A word can only end at end if it started within the longest word length, so the inner loop never needs to look further back than that.
def word_break(s, words):
vocab = set(words)
longest = max((len(w) for w in vocab), default=0)
ok = [False] * (len(s) + 1)
ok[0] = True # the empty prefix needs no words
for end in range(1, len(s) + 1):
for start in range(max(0, end - longest), end):
if ok[start] and s[start:end] in vocab:
ok[end] = True
break
return ok[len(s)]function wordBreak(s, words) {
const vocab = new Set(words);
let longest = 0;
for (const w of vocab) longest = Math.max(longest, w.length);
const ok = new Array(s.length + 1).fill(false);
ok[0] = true;
for (let end = 1; end <= s.length; end++) {
for (let start = Math.max(0, end - longest); start < end; start++) {
if (ok[start] && vocab.has(s.slice(start, end))) {
ok[end] = true;
break;
}
}
}
return ok[s.length];
}Trace dogsled with the vocabulary dog, dogs, led, sled. Positions 3 (dog) and 4 (dogs) become reachable from 0. Position 7 is reachable from 3 because sled is a word, and also from 4 because led is a word. ok[7] is true, so the answer is true. The break keeps the loop from doing extra work once a position is known to be reachable.
Getting the actual split
If the interviewer asks for the words, record where the last word started instead of a plain true. Walking those records back from the end produces the pieces in reverse order.
def one_split(s, words):
vocab = set(words)
came_from = [None] * (len(s) + 1)
came_from[0] = 0
for end in range(1, len(s) + 1):
for start in range(end):
if came_from[start] is not None and s[start:end] in vocab:
came_from[end] = start
break
if came_from[len(s)] is None:
return None
pieces, end = [], len(s)
while end > 0:
start = came_from[end]
pieces.append(s[start:end])
end = start
return pieces[::-1]Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Backtracking | Exponential in n in the worst case | O(n) call stack |
| Prefix table, look back to every start | O(n³) with slicing, O(n²) lookups | O(n + W) |
| Prefix table, look back at most L | O(n · L²) plus O(W) to build the set | O(n + W) |
| Trie walk from each reachable start | O(n · L) plus O(W) to build the trie | O(n + W) |
The extra L in the middle row comes from building and hashing each slice. Many answers quote O(n²) and stop there. Saying where the hidden factor comes from, and that a trie removes it, is the kind of detail that marks a careful answer.
Edge cases to test
- An empty text, which returns true under the usual convention.
- An empty vocabulary with a non-empty text, which returns false.
- A text that is exactly one word, and a text that is one word repeated many times.
- The long run of a's ending in a b, which separates a fast answer from a slow one.
- Overlapping words such as flow and flower, where only one choice may lead to a full split.
Common mistakes
- Matching the longest word first and never trying a shorter one.
- Forgetting ok[0] = true, so nothing ever becomes reachable.
- Keeping the vocabulary in a list, which turns each check into a linear scan.
- Returning true as soon as any word matches the start, without confirming the rest of the text can be split.
- Quoting O(n²) time while slicing strings inside the double loop.
How to explain it out loud
Fictional example
- Candidate
- My first idea is to peel off any vocabulary word that matches the front and recurse on the rest. That is correct, but on a string like many a's then a b it retries the same suffixes constantly.
- Candidate
- So I will store answers by position. ok[i] means the first i characters split cleanly. ok[0] is true, and ok[end] is true when some reachable start is followed by a word that ends at end.
- Candidate
- I only look back as far as the longest word, and the words go in a set. That makes it n times L slices, each costing up to L, so O(n L squared). If you want the words themselves, I can store where each reachable position came from.
Related problems
Longest Increasing Subsequence uses the same look-back-over-earlier-positions shape on numbers instead of text. Coin Change II also builds a total out of reusable pieces, but counts the ways rather than asking whether one exists. Both are good next steps once this table feels natural.
Practicing with Natively
Word Break rewards saying the recursion before the table, which is easy to skip under pressure. When you practice, Natively on Mac or Windows can read the prompt from a screenshot and suggest an approach to compare with your own attempt, and the transcript of a spoken mock lets you check whether you named the repeated subproblem before writing code. See how the AI interview assistant works.
Questions people ask
How do you solve Word Break?
Use dynamic programming over prefixes. ok[0] is true, and ok[end] is true when some earlier position start has ok[start] true and the slice from start to end is a dictionary word. The answer is ok[n].
What is the time complexity of Word Break?
With the look-back limited to the longest word length L, the table does about n times L slice checks, each costing up to L, so O(n · L²) plus the time to build the word set.
Why does a greedy longest-match approach fail for Word Break?
Taking the longest matching word first can leave a remainder no word covers, while a shorter first word would have worked. The table tries every possible last word instead of committing early.
How do you return the words, not just true or false?
For each reachable position, store where the last word started. If the end is reachable, walk those stored starts back to position 0 and reverse the pieces.
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.
