140. Word Break II
Asked at 15Bloomberg64Amazon50Meta34Google30Microsoft28Moveworks88ServiceNow55X94Dropbox92Snap85Uber50Anduril49TikTok46Oracle45Visa39
Problem
Insert spaces into s to split it into words from wordDict (words may be reused), and return every possible sentence, in any order.
Example: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"] → ["cats and dog","cat sand dog"]
Constraints: length ≤ 20; at most 10⁵ answers.
sentences(i) = all segmentations of s[i:]: for every dictionary word starting at i, prepend it to each sentence of the rest. Memoize by i.
Complexity: exponential output in the worst case; memoization avoids recomputation.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
words = set(wordDict)
@cache
def go(i):
if i == len(s):
return [""]
out = []
for j in range(i + 1, len(s) + 1):
if s[i:j] in words:
out += [s[i:j] + (" " + rest if rest else "") for rest in go(j)]
return out
return go(0)
assert sorted(Solution().wordBreak("catsanddog", ["cat", "cats", "and", "sand", "dog"])) == ["cat sand dog", "cats and dog"]
assert sorted(Solution().wordBreak("pineapplepenapple", ["apple", "pen", "applepen", "pine", "pineapple"])) == [
"pine apple pen apple", "pine applepen apple", "pineapple pen apple"]
assert Solution().wordBreak("catsandog", ["cats", "dog", "sand", "and", "cat"]) == []
class Solution {
private final Map<Integer, List<String>> memo = new HashMap<>();
public List<String> wordBreak(String s, List<String> wordDict) {
return go(s, 0, new HashSet<>(wordDict));
}
private List<String> go(String s, int i, Set<String> words) {
if (memo.containsKey(i)) return memo.get(i);
List<String> out = new ArrayList<>();
if (i == s.length()) out.add("");
for (int j = i + 1; j <= s.length(); j++) {
String w = s.substring(i, j);
if (!words.contains(w)) continue;
for (String rest : go(s, j, words)) out.add(rest.isEmpty() ? w : w + " " + rest);
}
memo.put(i, out);
return out;
}
}
func wordBreak(s string, wordDict []string) []string {
words := map[string]bool{}
for _, w := range wordDict {
words[w] = true
}
memo := map[int][]string{}
var gen func(i int) []string // all sentences for s[i:]
gen = func(i int) []string {
if i == len(s) {
return []string{""}
}
if out, ok := memo[i]; ok {
return out
}
out := []string{}
for j := i + 1; j <= len(s); j++ {
if w := s[i:j]; words[w] {
for _, rest := range gen(j) {
if rest == "" {
out = append(out, w)
} else {
out = append(out, w+" "+rest)
}
}
}
}
memo[i] = out
return out
}
return gen(0)
}