Skip to content

Word Break

MediumLeetCode #139Time O(n³)Space O(n + m)

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"] -> false

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]
  • 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 dp array is O(n); the set holds the dictionary’s m total characters.
  • 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 try j >= i - L. That cuts the work to roughly O(n · L²).
  • Index off-by-one. dp has n + 1 entries and dp[i] covers s[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.

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.

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]).