← Whiteboard questions

Word Break

Decide whether a text can be cut into words from a list

DSA, Medium, 1-D DP

Which structure or algorithm, and what does it cost.

You get a text text of lowercase letters and a list words of different lowercase words. Decide whether text can be cut, from left to right, into pieces that are all in words. A word may be used as many times as needed. Return true if a cut exists and false if not. An empty text can be cut into zero pieces.

Examples

Input text = "bluesky", words = ["blue", "sky", "bl"]
Output true
Why the cut is blue|sky. The word bl is a dead end, because uesky is not made of words.
Input text = "aaaaaaaab", words = ["a", "aa", "aaa"]
Output false
Why the final b is in no word, so no cut works, however many ways the a letters can be cut.
Input text = "", words = ["a"]
Output true
Why edge case: an empty text is cut into zero pieces.

Constraints

Your answer must contain

Target Aim for about O(n x L^2) time, with n the text length and L the longest word, and O(n) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Look at the last piece of a cut. It must be a known word. What must be true of the text in front of it?

Hint 2 the approach

For each length k, decide whether the first k letters can be cut. Think about how a decision for k uses decisions for shorter starts.

Hint 3 the key step

The first k letters can be cut if a word ends at k and the letters before it can be cut. The empty start is true. Try existing word lengths.

Walkthrough

Full walkthrough brute force to best

Brute force

Try every cut with recursion: at the front, try each word that matches, then cut the rest the same way. The same suffixes are tried again and again. With words a, aa and aaa and a text of 39 letters a and one b, the calls grow like 1.8^n, over 10^10 for 40 letters.

Better method

Memoised recursion. Let ok(i) say whether the letters from position i to the end can be cut. Save each answer, so every position is solved once. Each position tries the word lengths that exist. That is about O(n x L^2) time and O(n) memory, and the recursion goes n levels deep.

Best method

Let reach[i] say whether the first i letters can be cut into known words, with reach[0] true for the empty start. For each i, look at each distinct word length that fits. The first i letters can be cut if, for some length, the piece ending at i is a known word and reach[i - length] is true. Put the words in a set so each check is one lookup. Only lengths that occur in the list are tried, so there are at most L of them. This is correct because any cut ends with a last word, and the letters before it form a shorter start that was already decided. The answer is reach[n].

Hand trace

Run on bluesky with words blue, sky and bl. The word lengths are 2, 3 and 4. reach[0] is true. reach[1] is false, because no word is as short as 1. reach[2] is true: the word bl ends there and reach[0] is true. reach[3] is false: no word of length 2 or 3 ends at 3 after a true spot. reach[4] is true: blue ends there and reach[0] is true. reach[5] and reach[6] are false. reach[7] is true: sky ends there and reach[4] is true. The answer is true.

Code

def can_split(text, words):
    known = set(words)
    sizes = sorted({len(w) for w in words})
    reach = [False] * (len(text) + 1)
    reach[0] = True                 # reach[i]: the first i letters can be cut into known words
    for i in range(1, len(text) + 1):
        for size in sizes:
            if size > i:
                break
            if reach[i - size] and text[i - size:i] in known:
                reach[i] = True
                break
    return reach[len(text)]

Time and memory

O(n x L^2) time: n positions, at most L word lengths, and each piece lookup hashes up to L letters. For n = 2,500 and L = 12 that is about 360,000 letter steps. O(n + total word letters) memory.

Common mistakes

  • Taking the longest matching word at the front. With words ab, abc and cd, the text abcd needs ab|cd, but longest first takes abc and gets stuck on d.
  • Leaving out the empty start. If reach[0] is false, no cut can begin and every answer is false.
  • Using plain recursion with no saved answers. A text of many a letters and a final b takes a huge number of calls.

Related problems

More 1-D DP problems
Word Break: hints, walkthrough and Python solution