08. Word Break II
Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
How It Works & Algorithmic Design
Solves using DFS Backtracking with Hash Map Memoization:
- Memoization Map:
memo[index]stores list of valid sentences formable froms[index...]. - DFS Function
dfs(start):- Base Case: if
start === s.length, return[""]. - If
startinmemo, returnmemo[start]. - Loop
endfromstart + 1tos.length:- Extract
word = s.substring(start, end). - If
wordDict.has(word):- Recurse
subSentences = dfs(end). - Append
word + (sub ? " " + sub : "")tores.
- Recurse
- Extract
- Base Case: if
- Return:
memo[0].
Why This Approach Works Best
Memoization prunes duplicate invalid search branches, preventing exponential catastrophic backtracking.
Example Walkthrough
s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
Target text and words.
["cats and dog", "cat sand dog"]
Valid reconstructed sentence paths.
["cats and dog", "cat sand dog"]
Result array.
Answer: Word Break II Memoized DFS implementation
function wordBreak(s, wordDict) {
const set = new Set(wordDict);
const memo = new Map();
function dfs(start) {
if (memo.has(start)) return memo.get(start);
if (start === s.length) return [''];
const res = [];
for (let end = start + 1; end <= s.length; end++) {
const word = s.substring(start, end);
if (set.has(word)) {
const subs = dfs(end);
for (const sub of subs) {
res.push(word + (sub ? ' ' + sub : ''));
}
}
}
memo.set(start, res);
return res;
}
return dfs(0);
}Recursively construct sentences with dictionary words while storing suffix string results in a memoization map.
Use Hash Set for $O(1)$ word existence lookups.
Memoizing index search state cuts down repetitive sentence branching.
Exponential worst-case complexity $O(2^n)$ when all combinations are valid.