Word Break (LeetCode 139): Solution and Explanation

Medium
Array
Hash Table
String
Dynamic Programming
Trie
Memoization

Given a string s and a list of dictionary words, decide whether s can be split into a sequence of one or more dictionary words with nothing left over. Words may be reused any number of times.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force is a recursive search: at position 0, try every dictionary word that matches the start of the string, and for each match recurse on the rest. That explores every possible segmentation and can blow up exponentially on inputs like a long run of the letter a with words a, aa and aaa, because the same suffix gets solved again and again from different split paths.

The fix is to notice that the only thing that matters about a recursive call is where it starts. Whether the suffix beginning at index i can be segmented has a single yes or no answer, no matter how you got to i. So define dp[i] as true when s[i:] can be fully broken into words, and compute each answer once.

Filling the table from right to left makes every dependency ready before it is needed. The empty suffix at len(s) is trivially breakable, so dp[len(s)] = True. For each earlier i, try each word: if the word matches the text starting at i and dp[i + len(w)] is true, then dp[i] is true. The answer to the whole problem is dp[0].

Approach: Bottom-up DP over suffixes

  1. Create dp of length len(s) + 1, all false, and set dp[len(s)] = True for the empty suffix.
  2. Iterate i from len(s) - 1 down to 0.
  3. For each word w, check that it fits (i + len(w) <= len(s)) and that s[i : i + len(w)] == w.
  4. If it matches, set dp[i] = dp[i + len(w)], meaning the suffix is breakable if the rest after this word is breakable.
  5. As soon as dp[i] becomes true, break out of the word loop since one valid split is enough.
  6. Return dp[0].

Step-by-step example

s = "leetcode", wordDict = ["leet","code"]
  1. dp[8] = True for the empty suffix. All other entries start false.
  2. For i = 7, 6 and 5, neither four-letter word fits inside the remaining characters, so those entries stay false.
  3. i = 4: "leet" does not match s[4:8], but "code" does, so dp[4] = dp[8] = True.
  4. i = 3, 2, 1: the slices "tcod", "etco" and "eetc" match neither word, so those entries stay false.
  5. i = 0: "leet" matches s[0:4], so dp[0] = dp[4] = True. Return true.

Code: Python, Java, C++

1class Solution:
2    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
3        dp = [False] * (len(s) + 1)
4        dp[len(s)] = True
5        
6        for i in range(len(s) - 1, -1, -1):
7            for w in wordDict:
8                if (i + len(w)) <= len(s) and s[i : i + len(w)] == w:
9                    dp[i] = dp[i + len(w)]
10                if dp[i]:
11                    break
12        return dp[0]

Time and space complexity

Time

O(n × m × L)

For each of the n positions we try all m words, and comparing a slice against a word costs up to L, the maximum word length.

Space

O(n)

The dp array has n + 1 entries. Slices are temporary and at most L characters long.

Other approaches

Top-down recursion with memoization (time O(n × m × L), space O(n))

Write the natural recursive search from index i and cache each result in a dictionary. It has the same complexity as the table and can be easier to derive, but deep recursion on long strings may hit stack limits.

DP over end positions with a word set (time O(n × L²), space O(n + m × L))

Put the words in a hash set and, for each end index, check every start within the maximum word length. This is faster when the dictionary is large relative to the word lengths.

Common mistakes

  • Forgetting the base case dp[len(s)] = True, which leaves every entry false.
  • Using a greedy approach that always takes the longest matching word. With s = "goalspecial" and words "go", "goal", "goals" and "special", greedy grabs "goals" and gets stuck, while "goal" plus "special" works.
  • Not breaking once dp[i] is true. In this code a later matching word could overwrite a true value with false.
  • Indexing beyond the string when checking a word that is longer than the remaining suffix. Check i + len(w) <= len(s) first.

Frequently asked questions

Why does word break use dynamic programming?

The recursive search solves the same suffix many times from different split paths. Because whether a suffix is breakable does not depend on how you reached it, caching one answer per index removes all that repeated work.

What is the time complexity of word break?

With this table it is O(n × m × L): n positions, m dictionary words, and up to L characters compared per word. Space is O(n) for the table.

Can word break be solved with BFS?

Yes. Treat each index as a node and add an edge from i to i + len(w) whenever word w matches at i. A BFS from 0 with a visited set reaches len(s) exactly when the string can be segmented, with the same overall cost.

How do I return the actual sentences instead of true or false?

That is the follow-up problem, which needs backtracking with memoization to list every segmentation. The number of sentences can be exponential, so the output size dominates the cost.