Skip to content

Word Break

Decide whether a string can be cut into dictionary words, where each word may be used many times.

Medium1D Dynamic Programming
Solve on LeetCode

The problem

You get a string s and a list of words wordDict. Return true if s can be split into one or more pieces where every piece is a word from the list. The same word may be used any number of times.

Input s = "chaipani", wordDict = ["chai", "pani", "pan"]

Output true

chai + pani.

Input s = "samosas", wordDict = ["samosa", "sam", "osa"]

Output false

Both samosa and sam + osa leave the final s, which is not a word.

Key constraint: The string has at most 300 characters and words have at most 20, so from each position you only need to look back 20 characters.

How to spot the pattern

  • You must split a string into valid pieces, and pieces can repeat.
  • Whether the whole string works depends on whether some shorter prefix works.
  • Greedy choices, like always taking the longest matching word, can fail.

The idea

State: can[i] is true when the first i characters can be split into words, with can[0] = true for the empty prefix. That prefix works exactly when its last word, s[j..i - 1], is in the dictionary and the part before it, the first j characters, also works. So can[i] is true if some j < i has can[j] true and s[j..i - 1] in the word set, and can[n] is the answer.

Brute force: Recursively try every word as the next piece without saving results, which takes exponential time on inputs like a long run of a's.

Step by step

  1. 1Put the words in a hash set and note the length of the longest word.
  2. 2Make can of size n + 1 with only can[0] set to true.
  3. 3For each end i from 1 to n, try each start j from i - longest up to i - 1.
  4. 4If can[j] is true and s[j..i - 1] is in the set, set can[i] to true and stop trying starts.
  5. 5Return can[n].

See the pattern move

The 1d dynamic programming pattern on a small example. Step through it, or press play.

Code

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        words = set(wordDict)
        longest = max(len(w) for w in words)
        n = len(s)
        # can[i] is True when the first i characters split into dictionary words
        can = [False] * (n + 1)
        can[0] = True  # the empty prefix needs no words
        for i in range(1, n + 1):
            # the last word is s[j:i]; it can't be longer than the longest word
            for j in range(max(0, i - longest), i):
                if can[j] and s[j:i] in words:
                    can[i] = True
                    break
        return can[n]

Complexity

Time

O(n * L^2)

Space

O(n + D)

L is the longest word length: each of the n ends tries up to L starts, and cutting and hashing a piece costs O(L). The set stores all D characters of the dictionary.

Watch out for

  • Taking the longest matching word first: for abcd with the words abc, ab and cd, greedy takes abc and gets stuck.
  • Recursing without memoization, which explodes on inputs like 299 a's followed by a b.
  • Looking words up in a list instead of a set, which multiplies the work by the dictionary size.

Follow-up questions

What if you must return every possible sentence?

Memoize, for each start index, the list of sentences for the rest of the string. The output itself can be exponential, so this only works for small inputs; that is Word Break II.

Can a trie help?

Yes. From each start j with can[j] true, walk a trie of the words along s[j..] and mark can[end] for every word that ends, so you never build substrings.

In Hinglish

`can[i]` ka matlab hai: pehle `i` characters words mein toot sakte hain ya nahi. Aakhri word `s[j..i - 1]` dictionary mein ho aur `can[j]` true ho, toh `can[i]` bhi true.

Related problems