08. Word Break II

Difficulty:HardPattern:Memoized DFS BacktrackingTime:O(2^n)Space:O(2^n)

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:

  1. Memoization Map: memo[index] stores list of valid sentences formable from s[index...].
  2. DFS Function dfs(start):
    • Base Case: if start === s.length, return [""].
    • If start in memo, return memo[start].
    • Loop end from start + 1 to s.length:
      • Extract word = s.substring(start, end).
      • If wordDict.has(word):
        • Recurse subSentences = dfs(end).
        • Append word + (sub ? " " + sub : "") to res.
  3. Return: memo[0].

Why This Approach Works Best

Memoization prunes duplicate invalid search branches, preventing exponential catastrophic backtracking.

Example Walkthrough

Input

s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]

Target text and words.

Sentences

["cats and dog", "cat sand dog"]

Valid reconstructed sentence paths.

Output

["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.

Key Takeaways
  • 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.