Word Break
The problem
Section titled “The problem”Given a string s and a list of words, return true if s can be cut into pieces so
that every piece is a dictionary word. Words may be reused any number of times.
s = "applepenapple", words = ["apple", "pen"] -> true (apple + pen + apple)s = "catsandog", words = ["cats","dog","sand","and","cat"] -> falseKey insight
Section titled “Key insight”Trying every way to cut the string is exponential, and greedy fails: with "cars" and
["car", "ca", "rs"], taking car first dead-ends, but ca + rs works. The waste is
re-checking the same suffix from different earlier cuts.
Let dp[i] mean “the first i characters can be split into words”. Then
dp[i] = true if some j < i has dp[j] true and s[j:i] is in the dictionary, with
dp[0] = true (empty prefix). The answer is dp[n]. Put the words in a set so each
membership test is a hash lookup. Stop scanning j once dp[i] is true.
Show solutionHide solution
def word_break(s: str, word_dict: list[str]) -> bool: words = set(word_dict) n = len(s) dp = [True] + [False] * n # dp[i] = s[:i] can be split into dictionary words for i in range(1, n + 1): for j in range(i): if dp[j] and s[j:i] in words: dp[i] = True break return dp[n]export function wordBreak(s: string, wordDict: string[]): boolean { const words = new Set(wordDict); const n = s.length; const dp: boolean[] = new Array(n + 1).fill(false); // dp[i] = s[0..i) can be split into dictionary words dp[0] = true; for (let i = 1; i <= n; i++) { for (let j = 0; j < i; j++) { if (dp[j] && words.has(s.slice(j, i))) { dp[i] = true; break; } } } return dp[n];}import java.util.HashSet;import java.util.List;import java.util.Set;
class Solution { public boolean wordBreak(String s, List<String> wordDict) { Set<String> words = new HashSet<>(wordDict); int n = s.length(); boolean[] dp = new boolean[n + 1]; // dp[i] = s[0..i) can be split into dictionary words dp[0] = true; for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) { if (dp[j] && words.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[n]; }}Complexity
Section titled “Complexity”- Time: O(n³) — about n²/2 pairs
(j, i), and each one slices a substring and hashes it, which costs O(n). Many write O(n²), but that ignores the slice and hash cost. - Space: O(n + m) — the
dparray is O(n); the set holds the dictionary’smtotal characters.
Watch out for
Section titled “Watch out for”- Don’t claim O(n²) without caveat. The loops are n², but slicing and hashing a substring is linear in its length. Mention it; it shows you looked.
- Optional speed-up. If the longest word has length
L, only tryj >= i - L. That cuts the work to roughly O(n · L²). - Index off-by-one.
dphasn + 1entries anddp[i]coverss[0..i). Mixing up “prefix of length i” and “character at index i” is the classic bug. - Convert the list to a set first. Searching a list per substring adds another factor.
Variations
Section titled “Variations”Word Break II (LeetCode 140)
Section titled “Word Break II (LeetCode 140)”Return every valid sentence, not just yes or no. The trick: DFS with memoization on the start index, returning all sentences for each suffix. The output can be exponential in size, so the time bound is too.
Concatenated Words (LeetCode 472)
Section titled “Concatenated Words (LeetCode 472)”Find the words in a list that are built from at least two other words in the same list. The trick: run Word Break on each word against the rest of the set, requiring that the split uses at least two pieces (don’t let a word match itself).
Extra Characters in a String (LeetCode 2707)
Section titled “Extra Characters in a String (LeetCode 2707)”Break s into dictionary words while minimizing leftover characters. The trick: same
prefix DP, but dp[i] is the minimum leftover characters: either skip character i
(dp[i-1] + 1) or end a word there (dp[j]).