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 swordDictss
Example 1
Output: ["cat sand dog","cats and dog"]
Example 2
Output: ["pine apple pen apple","pine applepen apple","pineapple pen apple"]
Example 3
Output: []
The Idea
Imagine a message whose spaces were lost: catsanddog
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 sanddoganddog
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.
Now read catsanddog
The second question shows up in Example 2. Both "pine apple" and "pineapple" use up the first nine letters, leaving penapple
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
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 chch - 'a'
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, [""]
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[]
Saving each position's sentences
How do we avoid splitting penapple
The memo helps just as much when a position cannot be finished. In Example 3, catsandog
Java Solution
The method wordBreak
- First, build the trie. Each circle of the trie is a
object with an arrayNode of 26 links and a flagnext . For each wordisWord , a pointerw starts atcur and moves one letter down at a time, creating missing nodes, and the last node getsroot .isWord = true - Save
in a field and call a helper method,s , which returns every sentence for the letters ofsentencesFrom(start) from positions to the end. The answer isstart .sentencesFrom(0) - Inside the helper, look up
in the mapstart . If the list is already there, return it.memo - Otherwise, create the list
. Ifresult equalsstart , add one empty sentence, save it ins.length() and return it.memo - Walk the trie: a new pointer
starts atcur , and a loop movesroot fromend towards the end ofstart . Each step movess to the child for the letter atcur , and a missing child ends the loop.end - When
is a word end, take that piece ascur and callword for the rest. AddsentencesFrom(end + 1) alone for an empty rest, otherwiseword , a space and the rest.word - After the loop, store
inresult undermemo and return it.start
The main"aaaa"
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:
[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, []catsandog
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 [""][]catsanddog
Complexity
Thanks to the memo, each of the n positions of s
- 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