Python coding

Every way to split text into words

Someone removed the spaces from a sentence. Given the string text and a list words, return every way to put spaces back so that each piece is in words. A word may be used any number of times. Return each sentence once, as a string with single spaces, in any order; if text cannot be split, return an empty list.

Everything is lowercase a–z; 1 ≤ len(text) ≤ 30, and words may contain repeats. No test has more than 20 answers, but some have no answer and a huge number of dead ends: those must still finish fast.

  • word_splits("nowhere", ["no","now","where","here","he","re"]) → ["no where","now he re","now here"]
  • word_splits("icecream", ["ice","cream","icecream"]) → ["ice cream","icecream"]
  • word_splits("planet", ["plan","lane","net"]) → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Backtrack over cut points: from position start, try every dictionary word that begins there, append it to the path, recurse from where it ends, then pop it.

Hint 2

Keep the words in a set and only try pieces up to the longest word. When start reaches the end of the text, the path is one full sentence: join it with spaces.

Hint 3

The trap is a text with no split, like many a's and a final b: plain backtracking re-explores the same hopeless suffix again and again. Remember each start position that produced nothing.

Solution and why it works
pythonO(n·L²·(A + 1)), n = len(text), L = longest word, A = sentences returned · O(n) beyond the output
def word_splits(text: str, words: list[str]) -> list[str]:
    vocab = set(words)
    longest = max(map(len, vocab), default=0)
    dead = set()                         # start positions from which no split exists
    res, path = [], []

    def bt(start: int) -> bool:
        if start == len(text):
            res.append(" ".join(path))
            return True
        if start in dead:
            return False
        found = False
        for end in range(start + 1, min(len(text), start + longest) + 1):
            piece = text[start:end]
            if piece in vocab:
                path.append(piece)
                found = bt(end) or found
                path.pop()
        if not found:
            dead.add(start)              # never explore this suffix again
        return found

    bt(0)
    return res

Each level chooses the next word: a piece starting at start that is in the set; reaching the end means the path is a sentence. Whether a suffix can be finished depends only on where it starts, so a start that produced nothing goes into dead and is never explored again. Without that, "aaa…ab" tries every way to cut the a's before failing: exponential. Stopping at the first word that fits is wrong too: "no" and "now" can both open a sentence.