LeetCode #139 Medium

Word Break

Word Break is LeetCode 139 (Medium). Given a string s and a list of words wordDict, return true if s can be cut into pieces that are all dictionary words. A word may be used any number of times, and the pieces must cover the whole string with no gaps.

  • The answer is only yes or no. Listing every possible split is a different, harder task.
  • s has at most 300 characters, so an approach that looks at each position once and tries every word there is fast enough.
Constraints
  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • s and wordDict[i] consist of only lowercase English letters.
  • All the strings of wordDict are unique.
dpstringbacktracking
Open on LeetCode ↗
02

Intuition

Think of the gaps between characters as positions 0 to n. Position 0 is the start, position n is the end, and a dictionary word that fits at position i is a jump from i to i + len(word).

The question becomes: can a chain of jumps get from position 0 to position n? Mark position 0 as reached. Then go left to right, and from every reached position try each word; a word that fits marks where it ends as reached. Each position is handled once, so the shared middle parts of different splits are never recomputed.

How to spot this pattern

A string cut into valid pieces, with only a yes/no answer, is a one-dimensional DP over prefix lengths. When every split must be listed, as in Word Break II, the same positions are kept but each one stores its sentences.

03

Approach

Try it first

Before reading on, check cars with the words car, ca and rs by hand. Why does taking car first lead you astray, and what should you remember about positions instead?

1

Mark position 0 as reached

Make dp of size n + 1, all false, and set dp[0] = true. dp[i] means the first i characters can be split into words, and zero characters need no words at all.

2

Skip positions nothing reaches

Go through i = 0 … n − 1. If dp[i] is false, move on. No split of the string has a cut at i, so a word starting there can never be part of an answer.

3

From a reached position, try every word

For each word, check whether s continues with that word at index i. If it does, set dp[i + len(word)] = true: the prefix up to i splits into words, and one more word extends that split to the new position.

4

Read the answer at the end

Return dp[n]. It is true exactly when some chain of words starting at position 0 lands on the last position, which is a split of the whole string.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def wordBreak(self, s: str, wordDict: List[str]) -> bool:
▶3 n = len(s)
▶4 dp = [False] * (n + 1)
▶5 dp[0] = True
▶6 for i in range(n):
▶7 if not dp[i]:
▶8 continue
▶9 for word in wordDict:
▶10 if s.startswith(word, i):
▶11 dp[i + len(word)] = True
▶12 return dp[n]
leetcode012345678cutssposition 0 is reached: no letters, no words needed
dp[0]true
goalposition 8
Positions are the gaps between letters, 0 before the first and 8 after the last. The empty prefix needs no words, so position 0 is reached; the question is whether position 8 can be.
leetcode012345678leetcutss'leet' fits at 0 → reach position 4
i0
word'leet'
dp[4]true
The first 0 letters split into words, and 'leet' covers letters 0 to 3. So the first 4 letters split into words too.
leetcode012345678codecutss'code' does not match 'leet' → no jump
i0
word'code'
foundno
'code' does not match 'leet' at position 0, so this word gives no new position from here.
leetcode012345678cutssposition 1 not reached → skip it
i1
dp[i]false
No run of words ends at position 1, so no split of the string has a cut here. Words starting at 1 cannot help, and this position is skipped.
leetcode012345678cutssposition 2 not reached → skip it
i2
dp[i]false
No run of words ends at position 2, so no split of the string has a cut here. Words starting at 2 cannot help, and this position is skipped.
leetcode012345678cutssposition 3 not reached → skip it
i3
dp[i]false
No run of words ends at position 3, so no split of the string has a cut here. Words starting at 3 cannot help, and this position is skipped.
leetcode012345678leetcutss'leet' does not match 'code' → no jump
i4
word'leet'
foundno
'leet' does not match 'code' at position 4, so this word gives no new position from here.
leetcode012345678codecutss'code' fits at 4 → reach position 8
i4
word'code'
dp[8]true
The first 4 letters split into words, and 'code' covers letters 4 to 7. So the first 8 letters split into words too.
leetcode012345678cutssposition 5 not reached → skip it
i5
dp[i]false
No run of words ends at position 5, so no split of the string has a cut here. Words starting at 5 cannot help, and this position is skipped.
leetcode012345678cutssposition 6 not reached → skip it
i6
dp[i]false
No run of words ends at position 6, so no split of the string has a cut here. Words starting at 6 cannot help, and this position is skipped.
leetcode012345678cutssposition 7 not reached → skip it
i7
dp[i]false
No run of words ends at position 7, so no split of the string has a cut here. Words starting at 7 cannot help, and this position is skipped.
leetcode012345678cutssposition 8 reached → the string splits, true
dp[8]true
A chain of dictionary words runs from position 0 to position 8, so the whole string splits into words.
05

Common pitfalls

Taking the first word that fits and never looking back

✗ Wrong
at each position, take one matching word and move on
✓ Right
mark every position each matching word reaches

For s = "cars" with car, ca and rs, taking car leaves s, which matches nothing, so the answer comes out false. The split ca + rs works, and only remembering both positions 3 and 2 finds it.

Making the table one slot too short

✗ Wrong
dp = [False] * n
✓ Right
dp = [False] * (n + 1)

A word that ends at the last character marks position n, which needs slot n. For s = "a" with ["a"], the short table throws an index error instead of returning true.

06

Complexity

Time
O(n · m · k)
Space
O(n)
n is the length of s, m the number of words and k the longest word. Each of the n positions tries all m words, and each try compares up to k characters. Apart from the dictionary, only the n + 1 flags are stored.
07

Word Break FAQ

Why is plain recursion too slow when it gives the same answers?

Recursion that tries each word and recurses on the rest asks about the same leftover suffix again and again. For a string of 30 as ending in b, with words a, aa and aaa, the number of calls grows exponentially before every one of them fails. Caching the answer per start index fixes it, and that cache is this table read right to left.

Can a trie make it faster?

Yes, when the dictionary is large. Walk a trie of the words from position i along s; every word end you pass marks a reachable position. That checks all words starting at i in one walk of at most k characters, giving O(n · k) time after the trie is built.