Word Break
Difficulty: Medium
Given a string s and a list of words wordDict, return whether s can be split into one or more words from wordDict. Words can be reused any number of times.
Examples
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
"leetcode" splits into "leet" + "code".
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
"applepenapple" splits into "apple" + "pen" + "apple", reusing "apple".
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
No combination of the given words covers the whole string cleanly — "catsandog" always leaves a leftover chunk like "og" that isn't a word.
Constraints
1 <= s.length <= 300
1 <= wordDict.length <= 1000
s and every word in wordDict consist of lowercase English letters
Approach
Ask at each index i: can the rest of the string be split into dictionary words? Yes, if some word matches at i and the remainder after it can also be split. That's the same question, further along.
The base case is the empty remainder past the end, which is always true. Plain recursion asks "can this suffix be split?" many times through different paths. Caching each answer, or building them backward from the end, avoids the repeated work.
Solutions
Brute Force — Plain Recursion
From each position, try every dictionary word that matches there and recurse on the rest. Correct, but the same positions are re-explored through different word choices.
function wordBreak(s, wordDict) {
const words = new Set(wordDict);
function canBreak(start) {
if (start === s.length) return true;
for (const word of words) {
if (s.startsWith(word, start) && canBreak(start + word.length)) {
return true;
}
}
return false;
}
return canBreak(0);
}Time: O(2^n * m) — exponential branching, m = average word length for the startsWith checks · Space: O(n) — recursion depth
Optimal — Bottom-Up Tabulation
Work backward from the end. dp[i] records whether the suffix from i can be split into dictionary words, using dp values already solved for later positions.
function wordBreak(s, wordDict) {
const words = new Set(wordDict);
const n = s.length;
// dp[i] = can the suffix s[i..n) be broken into dictionary words?
const dp = new Array(n + 1).fill(false);
dp[n] = true; // the empty suffix is trivially breakable
for (let i = n - 1; i >= 0; i--) {
for (const word of words) {
if (s.startsWith(word, i) && dp[i + word.length]) {
dp[i] = true;
break;
}
}
}
return dp[0];
}Time: O(n * w * m) — n positions, w dictionary words, m average word length for matching · Space: O(n + w) — the dp array plus the word set