Word Break II

List every way to split a string into dictionary words, using a trie to find the words and saving the answer for each position.

Given a string s and a list of dictionary words wordDict, add spaces to s so that every piece between the spaces is a dictionary word. Return every sentence that can be made this way, in any order. A dictionary word may be used more than once. Both s and the words use lowercase English letters.

Example 1
Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
Output: ["cat sand dog","cats and dog"]
Example 2
Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
Output: ["pine apple pen apple","pine applepen apple","pineapple pen apple"]
Example 3
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: []
Solution

The Idea

Imagine a message whose spaces were lost: catsanddog. A person reading it tries a first word, checks that the rest still makes sense, and backs up when it does not. Here the job is to find every reading, not just one, using only the words in the dictionary.

Start reading Example 1 from the left. Both "cat" and "cats" are dictionary words, so the sentence can begin either way. After "cat", the letters sanddog are left, and they split as "sand dog". After "cats", the letters anddog are left, and they split as "and dog". Those are the two answers.

So every sentence is a first word followed by a sentence for the letters after it. That raises two questions. How do we find, quickly, every dictionary word that starts at a given position? And when two different first words leave the same letters behind, do we have to split those letters twice?

The first question is answered by storing the dictionary as a tree of letters. Look at the picture below. From the circle labelled root, each line carries one letter, and following lines spells a word: c, a, t spells "cat", and one more s spells "cats". A teal circle means a dictionary word ends there. A tree like this, where words that share a beginning share a path, is called a trie.

The string catsanddog with positions 0 to 9 above the trie of cat, cats, and, sand and dog. Walking from position 0 follows c, a, t, s. The word end cat leaves the rest at position 3, the word end cats leaves it at position 4, and the trie has no link for the next letter a, so the walk stops.

Now read catsanddog from position 0 while walking the orange path. After c, a and t, the walk reaches a teal circle, with the note that the word end "cat" leaves the rest at position 3. One letter later, the word end "cats" leaves the rest at position 4. The next letter is the "a" at position 4, and the trie has no line for it, so the walk stops. One walk found both first words and proved no longer word starts at 0.

The second question shows up in Example 2. Both "pine apple" and "pineapple" use up the first nine letters, leaving penapple, which starts at position 9. Its sentences are the same whichever first words led there, so they can be worked out once, saved under position 9, and reused.

Solution Approach

Turning that idea into code means seeing why trying every split is slow, then settling four things: the trie, the sentences for one position, the end of the string, and repeated work.

Trying every split

Why not try every way to place spaces? Between the 10 letters of catsanddog there are 9 gaps, each with or without a space, so there are 29 = 512 ways to cut it. Each extra letter doubles that, and almost all of the cuts contain a piece that is not a word.

Building the trie

What does one circle of the trie hold? It needs a link for each letter that can come next, and a mark saying whether a word ends there. Since the letters are a to z, the links fit in an array of 26, where the slot for letter ch is ch - 'a'. Adding a word walks down from the root, creates any missing circle on the way, and marks the last one.

Sentences from one position

How do we get every sentence for the letters from some position to the end? Walk the trie from that position, one letter at a time. At each word end, the word read so far is a possible first word, and the letters after it need the same question answered for a later position.

So the method that answers "every sentence from position 0" asks itself "every sentence from position 3" after "cat", and "every sentence from position 4" after "cats". A method that hands the shorter rest of the string back to itself like this is called recursive. It puts the first word in front of each sentence it gets back.

With a set of words instead, every possible piece from a position would be cut out and looked up, reading its letters again each time. The trie walk reads each letter once per position, and it stops at the first letter no word continues with, like the "a" at position 4 in the picture.

The end of the string

What should the method return once the position reaches the end, after "dog"? There are no letters left, and there is one way to split nothing: use no words. So the answer is a list holding one empty sentence, [""]. The caller then attaches "dog" to it alone, without a space, because the rest is empty.

An empty list would look just as natural, but it means "no way to finish". Then "dog" has nothing to attach to, nothing reaches position 0, and the whole answer for catsanddog comes out as [].

Saving each position's sentences

How do we avoid splitting penapple twice in Example 2? Keep a map from a position to its list of sentences. Before working out a position, look in the map; after working it out, store the list there. Keeping answers this way, so position 9 is worked out once and handed back the second time, is called memoization, and the map is the memo.

The memo helps just as much when a position cannot be finished. In Example 3, catsandog, both "cat sand" and "cats and" leave the rest at position 7, which is "og", and no word starts with it. The empty list for position 7 is worked out once and handed back the second time.

Java Solution

The method wordBreak works in these steps:

  1. First, build the trie. Each circle of the trie is a Node object with an array next of 26 links and a flag isWord. For each word w, a pointer cur starts at root and moves one letter down at a time, creating missing nodes, and the last node gets isWord = true.
  2. Save s in a field and call a helper method, sentencesFrom(start), which returns every sentence for the letters of s from position start to the end. The answer is sentencesFrom(0).
  3. Inside the helper, look up start in the map memo. If the list is already there, return it.
  4. Otherwise, create the list result. If start equals s.length(), add one empty sentence, save it in memo and return it.
  5. Walk the trie: a new pointer cur starts at root, and a loop moves end from start towards the end of s. Each step moves cur to the child for the letter at end, and a missing child ends the loop.
  6. When cur is a word end, take that piece as word and call sentencesFrom(end + 1) for the rest. Add word alone for an empty rest, otherwise word, a space and the rest.
  7. After the loop, store result in memo under start and return it.

The main method runs the three examples, then "aaaa" with the words "a" and "aa", and prints only how many sentences a run of 20 a's has with the same words.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WordBreakII {

    private static class Node {
        Node[] next = new Node[26];   // one link per letter a to z
        boolean isWord;               // a dictionary word ends here
    }

    private final Node root = new Node();
    private final Map<Integer, List<String>> memo = new HashMap<>();
    private String s;

    public List<String> wordBreak(String s, List<String> wordDict) {
        this.s = s;
        for (String w : wordDict) {
            Node cur = root;
            for (char ch : w.toCharArray()) {
                int i = ch - 'a';
                if (cur.next[i] == null) {
                    cur.next[i] = new Node();
                }
                cur = cur.next[i];
            }
            cur.isWord = true;
        }
        return sentencesFrom(0);
    }

    // All ways to split s from position start to the end into dictionary words.
    private List<String> sentencesFrom(int start) {
        if (memo.containsKey(start)) {
            return memo.get(start);
        }
        List<String> result = new ArrayList<>();
        if (start == s.length()) {
            result.add("");                       // one way to split nothing: no words
            memo.put(start, result);
            return result;
        }
        Node cur = root;
        for (int end = start; end < s.length(); end++) {
            cur = cur.next[s.charAt(end) - 'a'];
            if (cur == null) {
                break;                            // no dictionary word goes on this way
            }
            if (cur.isWord) {
                String word = s.substring(start, end + 1);
                for (String rest : sentencesFrom(end + 1)) {
                    result.add(rest.isEmpty() ? word : word + " " + rest);
                }
            }
        }
        memo.put(start, result);
        return result;
    }

    public static void main(String[] args) {
        System.out.println(new WordBreakII().wordBreak("catsanddog",
                List.of("cat", "cats", "and", "sand", "dog")));
        System.out.println(new WordBreakII().wordBreak("pineapplepenapple",
                List.of("apple", "pen", "applepen", "pine", "pineapple")));
        System.out.println(new WordBreakII().wordBreak("catsandog",
                List.of("cats", "dog", "sand", "and", "cat")));
        System.out.println(new WordBreakII().wordBreak("aaaa", List.of("a", "aa")));
        System.out.println(new WordBreakII().wordBreak("a".repeat(20), List.of("a", "aa")).size());
    }
}

Running it prints:

Output
[cat sand dog, cats and dog]
[pine apple pen apple, pine applepen apple, pineapple pen apple]
[]
[a a a a, a a aa, a aa a, aa a a, aa aa]
10946

Look at the first line: "cat sand dog" comes before "cats and dog". The walk from position 0 meets the word end for "cat" one letter before the one for "cats", so that order follows the trie walk. The third line, [], is catsandog: its one d is taken by "sand" or "and", so "og" is always left over.

The fourth line lists five sentences for just four letters, from four single a's to two copies of "aa". The last line, 10946, is the count for 20 a's. The number of sentences, and so the output, can grow far faster than the string, and no method can return them all in less time than it takes to write them.

The empty sentence at the end of the string is what starts every sentence. A copy of the method that returns an empty list there instead of [""] prints [] for catsanddog, because no sentence is ever started.

Complexity

Thanks to the memo, each of the n positions of s is worked out once, so the cost is the trie walks plus the sentences themselves.

  • Time: O(n · L + total length of the sentences built), because each of the n positions walks at most L letters into the trie, L being the longest word, and each sentence is built letter by letter. The second part can grow exponentially, as the 10946 sentences for 20 a's show.
  • Space: O(trie size + total length of the saved sentences), because the trie has at most one node per letter of the words, the memo keeps every position's sentences, and at most n + 1 recursive calls are open at once.

When the question is only whether some split exists, a yes or no is enough, and the sentences never need to be built: see Word Break.