#139

Word Break

Medium Prefix DP

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Decide whether a string can be split into a sequence of words from a dictionary (words can be reused).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: can the string be split into dictionary words?

Why this works: ok[i] = the first i letters can be split. ok[i] is true if some ok[j] is true and s[j..i) is a word.

Example: "leetcode", ["leet", "code"]

ok[4] (leet) ✓ → ok[8] (code) ✓ → true

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Greedy matching of the longest word first — it can block a valid split.

Solve on LeetCode ↗
Complexity
  • Time: O(n · L) substring checks, L = longest word.
  • Space: O(n).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon