Word Break

Decide whether a string can be cut into words from a dictionary, where a word may be used more than once.

Given a string s and a list of words wordDict, return true if s can be cut into a sequence of one or more words from the list, with no letters left over. The same word may be used more than once.

Example 1
Input: s = "sunflower", wordDict = ["sun", "flower"]
Output: true
Explanation: "sunflower" is "sun" followed by "flower".
Example 2
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: "apple" is used twice.
Example 3
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
Solution

The Idea

Picture a sign painted with no spaces: CATSANDOG. To read it, you look for where one word ends and the next one begins. This problem asks the same thing: can s be cut into pieces so that every piece is a word from wordDict?

Example 1 is quick, because "sunflower" is "sun" and then "flower". Example 3 takes more tries. Starting with "cat" leaves "sandog", "sand" fits next, and that leaves "og", which no word matches. Starting with "cats" instead leaves "andog", "and" fits, and once again "og" is left over.

Two different starts ran into the same leftover. In a longer string this happens again and again, and trying every possible cut repeats the same work many times. So what really matters about a partly finished cut? Only where it stops. After "cat" + "sand" or after "cats" + "and", we stand at the same spot, just before "og", and the words that brought us there make no difference.

Number the gaps between the letters of "catsandog" as positions: position 0 is before the c, and position 9 is after the g. Call a position reachable when the letters before it can be cut into words. Look at the picture below.

The letters of catsandog with positions 0 to 9 between them. The words cat and cats start at position 0 and end at 3 and 4, and sand and and both end at 7, so positions 0, 3, 4 and 7 are marked yes. The word dog ends at position 9 but starts at position 6, which is marked no, so position 9 is no.

Position 0 is reachable with no words at all, so the row labelled "can split up to here?" says yes under it. The words "cat" and "cats" start at position 0, which makes positions 3 and 4 yes. The word "sand" starts at 3 and "and" starts at 4, and both end at 7, so position 7 is yes as well.

Now look at the orange dashed "dog". It does end at position 9, the end of the string, but it starts at position 6, and position 6 is no. No other word ends at 9, so position 9 stays no, and the answer for Example 3 is false.

So a position is reachable when some word ends there and starts at an earlier position that is reachable. Each yes or no is built from the ones to its left, worked out once and kept. Solving the whole string this way, from stored answers for its shorter beginnings, is called dynamic programming.

Solution Approach

Turning that idea into code means settling four things: why trying every cut is slow, what each stored answer holds, how one answer is worked out from earlier ones, and how to look up words quickly. One optional change then skips checks that can never match.

Trying every cut

Why not simply try every way to cut the string? A method can take each word that matches the front of s and then call itself on the letters that are left. For "catsandog", that search checks the leftover "og" twice, once after "cat" + "sand" and once after "cats" + "and".

With the string "aaaaaaab" and the words "a", "aa" and "aaa", it gets much worse. There are 44 ways to cut the seven a's into those words, and every one of them ends at the same b, which no word matches. Keeping one yes or no per position, as in the picture, settles each position once, however many ways lead to it.

What each stored answer holds

What should be stored? One true or false per position, so a boolean array named canSplit with n + 1 entries, where n is the number of letters in s. The entry canSplit[i] is true when the first i letters can be cut into words. It is the yes or no under position i in the picture.

Where does it start? The first entry, canSplit[0], is true, because no letters need no words, and that lets a word at the very front count. The answer for the whole string is canSplit[n].

Working out one position

How is canSplit[i] decided? Try every earlier position j as the start of the last word. If canSplit[j] is true and the letters from position j to position i form a word, then position i is reachable too. For position 7 in "catsandog", j = 3 works: position 3 is yes, and the letters from 3 to 7 spell "sand".

One working j is enough, so the search for position i stops at the first one. The positions are decided from left to right, so every canSplit[j] that position i needs is already known.

Looking up words

Each check asks whether a piece of s is one of the dictionary words. In a list, checking the piece "sand" means comparing it with "cats", "dog" and then "sand", one by one. Here the words are copied into a HashSet<String> named words first, so words.contains("sand") uses the hash code of "sand" to jump to the one spot where it would be stored.

Skipping starts that are too far back

This last change is optional. In Example 3 the longest words, "cats" and "sand", have four letters, so a last word that starts more than four positions before i can never match. Starting j at i minus the longest word length skips those checks and gives the same answers. It saves the most when the words are short and s is long.

Java Solution

The method wordBreak works in these steps:

  1. First, copy wordDict into a HashSet named words with new HashSet<>(wordDict), so each word check is a set lookup.
  2. Create the boolean array canSplit with n + 1 entries, where n is s.length(), and set canSplit[0] to true for the empty start.
  3. Decide the positions from left to right with two loops, one inside the other. The outer loop moves i from 1 to n, the position being decided. Inside, a second loop moves j from 0 to just before i, the possible start of the last word.
  4. If canSplit[j] is true and words contains s.substring(j, i), set canSplit[i] to true and break out of the inner loop. The canSplit[j] test comes first, so no substring is made for a position that is not reachable.
  5. After both loops, return canSplit[n], the answer for the whole string.

The main method runs the three examples, then "goalspecial" with the words "go", "goal" and "special", "aaaaaaab" with "a", "aa" and "aaa", and "cat" with only the word "cats".

Java
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class WordBreak {

    public static boolean wordBreak(String s, List<String> wordDict) {
        Set<String> words = new HashSet<>(wordDict);
        int n = s.length();
        boolean[] canSplit = new boolean[n + 1];   // canSplit[i]: the first i letters split
        canSplit[0] = true;                        // no letters need no words
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < i; j++) {
                if (canSplit[j] && words.contains(s.substring(j, i))) {
                    canSplit[i] = true;            // a word from j to i ends here
                    break;
                }
            }
        }
        return canSplit[n];
    }

    public static void main(String[] args) {
        System.out.println(wordBreak("sunflower", List.of("sun", "flower")));
        System.out.println(wordBreak("applepenapple", List.of("apple", "pen")));
        System.out.println(wordBreak("catsandog", List.of("cats", "dog", "sand", "and", "cat")));
        System.out.println(wordBreak("goalspecial", List.of("go", "goal", "special")));
        System.out.println(wordBreak("aaaaaaab", List.of("a", "aa", "aaa")));
        System.out.println(wordBreak("cat", List.of("cats")));
    }
}

Running it prints:

Output
true
true
false
true
false
false

The answers true, true and false on the top three lines match Examples 1 to 3. The fourth line, true for "goalspecial", is worth a closer look. A cut that always takes the shortest word matching at the front takes "go", then finds no word starting with "al" and gives up. The two loops also try "goal", which reaches position 4, and "special" carries on from there to position 11, the end.

The fifth line is false: however the seven a's are grouped, the b at the end is left over, because no word matches it. The last line is false too, because "cats" is one letter longer than "cat" and so never matches any piece of it.

The original implementation, WordBreak.java, is on GitHub.

Complexity

The work is the two loops over pairs of positions, with a substring and a set lookup for each pair.

  • Time: O(n³), because the loops try about n²/2 pairs of positions j and i in a string of n letters, and each substring and hash lookup reads up to n letters.
  • Space: O(n) plus the word set, because canSplit keeps one true or false for each of the n + 1 positions, and only one substring is made at a time.

Listing every possible cut instead of only answering true or false is Word Break II.