Word Break
Medium · Dynamic programming
Jump to codeDecide whether a string can be split into one or more words from a dictionary of nonempty strings. Dictionary words can be reused. Treat an empty input as segmentable.
Examples
Example 1
s = "leetcode" wordDict = ["leet","code"]
Output: true
Example 2
s = "applepenapple" wordDict = ["apple","pen"]
Output: true
Constraints
- 1 <= s.length <= 200
- 1 <= wordDict.length <= 100
- 1 <= wordDict[i].length <= 20
- s and wordDict[i] consist of only lowercase English letters.
Need a hint?
Ask whether each prefix can end with a dictionary word.
Asked in real interviews
Candidates reported versions of Word Break from these company interviews. Some company questions are locked and open with Premium or XP.
- Determine string segmentability with dictionaryAmazon
- Insert Spaces to Rebuild a Sentence from Dictionary WordsMicrosoft
Solution approach
Let dp[0] be true. For each endpoint, test candidate start positions up to the maximum dictionary word length earlier. If dp[start] is true and s[start:end] is a dictionary word, mark the endpoint reachable. Return dp[len(s)]. Account for substring copying when analyzing runtime.
Complexity
O(nL²) time with O(L)-cost substring creation and hashing, O(n + dictionary size) space; L is maximum word length.
Python reference solution
def wordBreak(s, wordDict):
words = set(wordDict)
longest = max(map(len, words), default=0)
possible = [True] + [False] * len(s)
for end in range(1, len(s) + 1):
possible[end] = any(possible[start] and s[start:end] in words
for start in range(max(0, end - longest), end))
return possible[-1]
JavaScript solution
function wordBreak(s, wordDict) {
const words = new Set(wordDict);
let longest = 0;
for (const word of words) longest = Math.max(longest, word.length);
const possible = Array(s.length + 1).fill(false);
possible[0] = true;
for (let end = 1; end <= s.length; end++) {
for (let start = Math.max(0, end - longest); start < end; start++) {
if (possible[start] && words.has(s.slice(start, end))) { possible[end] = true; break; }
}
}
return possible[s.length];
}
Java solution
import java.util.*;
class Solution {
public boolean wordBreak(String s, String[] wordDict) {
Set<String> words = new HashSet<>(Arrays.asList(wordDict));
int longest = 0;
for (String word : words) longest = Math.max(longest, word.length());
boolean[] possible = new boolean[s.length() + 1];
possible[0] = true;
for (int end = 1; end <= s.length(); end++) {
for (int start = Math.max(0, end - longest); start < end; start++) {
if (possible[start] && words.contains(s.substring(start, end))) { possible[end] = true; break; }
}
}
return possible[s.length()];
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool wordBreak(string s, vector<string> &wordDict) {
unordered_set<string> words(wordDict.begin(), wordDict.end());
int longest = 0;
for (const string& word : words) longest = max(longest, (int)word.size());
vector<bool> possible(s.size() + 1);
possible[0] = true;
for (int end = 1; end <= (int)s.size(); end++) {
for (int start = max(0, end - longest); start < end; start++) {
if (possible[start] && words.count(s.substr(start, end - start))) { possible[end] = true; break; }
}
}
return possible[s.size()];
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
"leetcode",
[
"leet",
"code"
]
]true
[
"applepenapple",
[
"apple",
"pen"
]
]true
[
"catsandog",
[
"cats",
"dog",
"sand",
"and",
"cat"
]
]false
[
"aaaaaaa",
[
"aaaa",
"aaa"
]
]true
[
"abcd",
[
"a",
"abc",
"b"
]
]false
Drafts are saved per language in this browser when storage is available.