Home
DSA Patterns
Dynamic Programming
Word Break
Word Break (LeetCode 139)
Word Break (LeetCode 139): decide whether the string s can be cut, end to end, into pieces that each appear in a given list of dictionary words, where any word may be used more than once.
Examples
The cut at 4 reaches "leet", and "code" finishes it.
Dictionary words may be reused, so "apple" is used twice.
Both "cats" and "cat" start it, but neither leaves a remainder the dictionary can finish.
Problem Understanding
We need to check if the entire string can be built using dictionary words. Words can be reused.
Example: s = "leetcode", dict = ["leet", "code"]
- "leet" + "code" -> Valid
- Output:
true
Algorithm Strategy
Let dp[i] be true when the first i characters can be cut into dictionary words.
Recurrence: dp[i] is true if there is some j < i where
dp[j]is true: the firstjcharacters already segment, ands[j...i)is in the dictionary.
Base case: dp[0] = true. The empty prefix needs no words, and it is what the first real word stands on.
One working j settles the question, so the inner loop stops at the first one it finds.
Interactive Visualization
COLUMN i = THE FIRST i CHARACTERS · T = REACHABLE · OUTLINED = THE CUT POINT AND THE PIECE BEING TESTED
BASE CASE: THE EMPTY PREFIX IS REACHABLE
0
1
2
3
4
5
6
7
8
s
dp
reachable
1/9
testing
:
Answer
:
dictionary
The empty prefix needs no words, so dp[0] is true: every segmentation starts from here
Next
Can the first 1 character, "l", be cut into words? Try every cut point
string, then words
Column i is the verdict on the first i characters. When a cut point is tested, its cell and the letters of the piece between it and i light together, so dp[j] and s[j:i] in words can be read straight off the picture.
Try Example 3: "cats" and "cat" both start it, and neither leaves a remainder the dictionary can finish.
Dry Run
s = "applepen", dict = ["apple", "pen"]
| i | Substr tested | Valid split at j? | dp[i] Result |
|---|---|---|---|
| 0 | "" | - | T (Base) |
| ... | ... | ... | ... |
| 5 | "apple" | j=0 (dp[0]=T) & "apple" in dict |
T |
| ... | ... | ... | ... |
| 8 | "pen" (from 5) | j=5 (dp[5]=T) & "pen" in dict |
T |
Edge Cases & Common Mistakes
Common pitfalls:
Words may be reused. "applepenapple" needs "apple" twice, and nothing in the recurrence forbids it: dp never tracks which words were spent.
dp[0] = true is what starts it. Without it no first word can ever be accepted, because every cut of a prefix has to stand on an earlier true cell.
An early word is not a commitment. "catsandog" reaches "cats" and gets stuck, and reaching "cat" does not help either. Only a false at dp[n] settles it.
Solution
Every cut point tried, stopping at the first that works: the lines light up as the figure above steps.
Word Break Code
1var wordBreak = function(s, wordDict) {2 const n = s.length;3 const words = new Set(wordDict);4 const dp = new Array(n + 1).fill(false);5 dp[0] = true;6 for (let i = 1; i <= n; i++) {7 for (let j = 0; j < i; j++) {8 if (dp[j] && words.has(s.slice(j, i))) {9 dp[i] = true;10 break;11 }12 }13 }14 return dp[n];15};
Word Break in Python, Java, C++, TypeScript and C
Word Break in Python
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
words = set(wordDict)
dp = [False] * (n + 1)
dp[0] = True
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]Word Break in Java
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int n = s.length();
Set<String> words = new HashSet<>(wordDict);
boolean[] dp = new boolean[n + 1];
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];
}
}Word Break in C++
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int n = s.size();
unordered_set<string> words(wordDict.begin(), wordDict.end());
vector<bool> dp(n + 1, false);
dp[0] = true;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && words.count(s.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
};Word Break in TypeScript
function wordBreak(s: string, wordDict: string[]): boolean {
const n = s.length;
const words = new Set(wordDict);
const dp: boolean[] = new Array(n + 1).fill(false);
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];
}Word Break in C
/* No hash set in the standard library, so the dictionary is scanned. That costs a factor of d
over the hashed versions above; a trie removes it. */
static bool inDict(const char* piece, int len, char** wordDict, int size) {
for (int w = 0; w < size; w++) {
if ((int)strlen(wordDict[w]) == len && strncmp(piece, wordDict[w], len) == 0) return true;
}
return false;
}
bool wordBreak(char* s, char** wordDict, int wordDictSize) {
int n = strlen(s);
bool* dp = (bool*)calloc(n + 1, sizeof(bool));
dp[0] = true;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && inDict(s + j, i - j, wordDict, wordDictSize)) {
dp[i] = true;
break;
}
}
}
bool result = dp[n];
free(dp);
return result;
}More practice: DSA interview questions with answers · patterns cheat sheet
