Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get a string s and a list of words wordDict. Return true if you can cut s into one or more pieces so that every piece is a word from the list. You can use a word as many times as you like, and you don't have to use every word.
s has 1 to 300 lowercase letters. The list has 1 to 1000 distinct words, each 1 to 20 letters. Below, n = len(s), m is the number of words and k is the longest word's length.
Example: s = "applepenapple", wordDict = ["apple", "pen"] → true, because it splits as apple | pen | apple.
Start with brute force
Try every way to cut the string. Between each pair of neighbouring characters you either cut or you don't, so there are 2ⁿ⁻¹ ways. Check each one against the dictionary.
With n = 300 that's about 10⁹⁰ ways. A smarter recursion ("try each word as the first piece, then recurse on the rest") still blows up on inputs like "aaaa…ab" with words "a", "aa", "aaa": it explores a huge number of splits of the as, and every one fails at the b.
Building the intuition
Look at what that recursion actually asks. On "aaaa…ab" it asks "can the rest, starting at position 7, be split?" many times, once for every way of splitting the first 7 characters. The answer never changes. How you split the beginning doesn't matter, only where it ended.
So the question depends on one number, a position. Store one yes/no answer per position. Walk through the recipe:
- State.
dp[i]means the firsticharacters,s[0:i], can be split into dictionary words. - Recurrence. Think about the last word of the split. If the last word is
w, thens[0:i]must end withw, and the part before it,s[0:i − len(w)], must be splittable. Sodp[i]is true when some wordwhasdp[i − len(w)]true andshaswending exactly at positioni. - Base case.
dp[0] = true. The empty prefix is split into zero words. Without this, no first word could ever start. - Order.
dp[i]reads smaller indices only, so fillifrom 1 ton. The answer isdp[n].
This is the same shape as Coin Change: there, the last coin left an amount to make; here, the last word leaves a prefix to split.
The optimal approach
- Make
dpof sizen + 1, all false. Setdp[0] = true. - For
ifrom 1 ton, for each wordwof lengthL:- if
L ≤ i,dp[i − L]is true, andshaswstarting ati − L, setdp[i] = trueand stop trying words for thisi.
- if
- Return
dp[n].
The subtle detail: check dp[i − L] before comparing strings. The string comparison costs up to k steps; the table lookup costs one. Testing the cheap condition first skips most comparisons. And break as soon as one word works: you only need one way.
Another way to write step 2: put the words in a hash set and, for each i, try every start j from i − k to i − 1, checking dp[j] and whether s[j:i] is in the set. Same idea; looping over words is simpler and avoids building substrings.
Space. One 1D table, and any earlier cell may be needed later, so there's nothing to squeeze.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
# dp[i] = True when the first i characters, s[0:i], can be split into dictionary words
dp = [False] * (n + 1)
dp[0] = True # the empty prefix needs no words
for i in range(1, n + 1):
for w in wordDict:
L = len(w)
# w can be the LAST word of s[0:i] if it fits, the part before it splits,
# and s really ends with w at position i
if L <= i and dp[i - L] and s.startswith(w, i - L):
dp[i] = True
break # one way is enough
return dp[n]class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int n = s.size();
// dp[i] = true when the first i characters, s[0..i), can be split into dictionary words
vector<bool> dp(n + 1, false);
dp[0] = true; // the empty prefix needs no words
for (int i = 1; i <= n; i++) {
for (const string& w : wordDict) {
int L = w.size();
// w can be the LAST word of s[0..i) if it fits, the part before it splits,
// and s really ends with w at position i
if (L <= i && dp[i - L] && s.compare(i - L, L, w) == 0) {
dp[i] = true;
break; // one way is enough
}
}
}
return dp[n];
}
};class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int n = s.length();
// dp[i] = true when the first i characters, s[0..i), can be split into dictionary words
boolean[] dp = new boolean[n + 1];
dp[0] = true; // the empty prefix needs no words
for (int i = 1; i <= n; i++) {
for (String w : wordDict) {
int L = w.length();
// w can be the LAST word of s[0..i) if it fits, the part before it splits,
// and s really ends with w at position i
if (L <= i && dp[i - L] && s.startsWith(w, i - L)) {
dp[i] = true;
break; // one way is enough
}
}
}
return dp[n];
}
}/**
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
var wordBreak = function (s, wordDict) {
const n = s.length;
// dp[i] = true when the first i characters, s[0..i), can be split into dictionary words
const dp = new Array(n + 1).fill(false);
dp[0] = true; // the empty prefix needs no words
for (let i = 1; i <= n; i++) {
for (const w of wordDict) {
const L = w.length;
// w can be the LAST word of s[0..i) if it fits, the part before it splits,
// and s really ends with w at position i
if (L <= i && dp[i - L] && s.startsWith(w, i - L)) {
dp[i] = true;
break; // one way is enough
}
}
}
return dp[n];
};Dry run
s = "catsanddog", wordDict = ["cat", "cats", "and", "sand", "dog"]. Positions are counted in characters: dp[4] is about "cats".
| i | prefix s[0:i] | word that ends here and fits | checks dp[i − L] | dp[i] |
|---|---|---|---|---|
| 0 | "" | — | — | T (base) |
| 1 | c | none | — | F |
| 2 | ca | none | — | F |
| 3 | cat | cat | dp[0] = T | T |
| 4 | cats | cats | dp[0] = T | T |
| 5 | catsa | none (dp[2], dp[1] are F) | — | F |
| 6 | catsan | none (san isn't a word, dp[2] is F) | — | F |
| 7 | catsand | and | dp[4] = T | T |
| 8 | catsandd | none | — | F |
| 9 | catsanddo | none | — | F |
| 10 | catsanddog | dog | dp[7] = T | T |
Final table: dp = [T, F, F, T, T, F, F, T, F, F, T]. dp[10] is true: cats | and | dog. (At i = 7, sand with dp[3] would also have worked; and was tried first and the loop stopped.)
Complexity
- Time: O(n · m · k). For each of the
npositions, trymwords, and a comparison costs up tok. At most 300 × 1000 × 20 = 6 million steps, and thedpcheck skips most comparisons. - Space: O(n) for the table.
Edge cases and traps
- Forgetting
dp[0] = true. Then nothing is ever true and you always return false. - Greedy matching. Taking the longest word at each point fails:
"cars"with["car", "ca", "rs"]only splits asca | rs; greedycarleavess. - Words used more than once.
"aaaaaaa"with["aaaa", "aaa"]isaaa | aaaa. Reuse is allowed. - Plain recursion without a memo. Correct, but times out on
"aaa…ab". - Off-by-one in the slice. The word ending at
istarts ati − Land coverss[i − L : i].
Say it in the interview
"Let
dp[i]be whether the firsticharacters can be split. The last word of a split is somew, sodp[i]is true ifdp[i − len(w)]is true andsends withwat positioni.dp[0]is true for the empty prefix. I fill it left to right and returndp[n]. That's O(n times words times word length) time and O(n) space. It's the same shape as Coin Change, with words instead of coins."
Follow-ups interviewers ask
- "Return every possible split, not just yes or no." That's Word Break II: backtracking over the words, with a memo from position to the list of splits of the rest. The output itself can be exponential.
- "The dictionary is huge." Put it in a trie and walk forward from each true position. You stop as soon as no word continues, instead of trying every word.
- "Can you use a set instead of looping over words?" Yes: for each
i, try startsjfromi − ktoi − 1, which is O(n · k) set lookups of strings up to lengthk.
Practise the same idea
This is Day 86 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free