SDE & MLE Prep

140. Word Break II

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)