sagelearnai

Word Break II

Difficulty: Hard · Pattern: Backtracking · LeetCode #140

Insert spaces into s to build sentences in which every word is in wordDict (words may be reused). Return all such sentences, in any order.

Examples

text
s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
→ ["cats and dog","cat sand dog"]
s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
→ ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
s = "catsandog", same dict  →  []

Hints

  1. Word Break I asks whether a split exists. Here you need all of them, so it's backtracking.
  2. Memoize sentences(i), the list of sentences for the suffix s[i:]. Then shared suffixes are computed once.

Approach

text
memo = {}
go(i):
    if i == n: return [""]
    res = []
    for each word w in dict with s.startswith(w, i):
        for rest in go(i + len(w)):
            res.append(w if rest == "" else w + " " + rest)
    memo[i] = res

Memoization helps when many split paths share a suffix. The output itself can be exponential (e.g. "aaaa…" with ["a","aa","aaa"]), so no algorithm beats output size. A cheap Word Break I check first avoids exploring unsplittable inputs like "aaaa…ab".

Complexity

Time: O(n² + output size). Space: O(n · output) for the memo.

Python solution
def wordBreak(s, wordDict):
    words = set(wordDict)
    lens = sorted({len(w) for w in words})
    memo = {}
    def go(i):
        if i == len(s):
            return ['']
        if i in memo:
            return memo[i]
        res = []
        for L in lens:
            w = s[i:i + L]
            if len(w) == L and w in words:
                for rest in go(i + L):
                    res.append(w if not rest else w + ' ' + rest)
        memo[i] = res
        return res
    return go(0)
JavaScript solution
function wordBreak(s, wordDict) {
  const words = new Set(wordDict), memo = new Map();
  const go = (i) => {
    if (i === s.length) return [''];
    if (memo.has(i)) return memo.get(i);
    const res = [];
    for (let j = i + 1; j <= s.length; j++) {
      const w = s.slice(i, j);
      if (!words.has(w)) continue;
      for (const rest of go(j)) res.push(rest ? w + ' ' + rest : w);
    }
    memo.set(i, res);
    return res;
  };
  return go(0);
}