Word Break
Word Break is a medium dynamic programming problem solved with the 1d dp pattern.
The best approach, optimal (1d dp over prefixes), runs in O(n · L²) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from recursion up.
Problem
Given a string s and a dictionary of words, decide whether s can be split into a sequence of one or more dictionary words. Words may be reused.
Examples
Example 1
- Input
s = "leetcode", wordDict = ["leet", "code"]- Output
true
Example 2
- Input
s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]- Output
false
Constraints
1 <= s.length <= 300; up to 1000 words of length 1 to 20.- Dictionary words may be reused.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Recursion | O(2ⁿ) | O(n) |
| Optimal (1D DP over prefixes) | O(n · L²) | O(n) |
1Recursion
O(2ⁿ)O(n)Try every dictionary word as a prefix and recurse on the rest.
- If start == n return true.
- For each end: if s[start..end) is a word and rec(end), return true.
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
return can(s, 0, new HashSet<>(wordDict));
}
private boolean can(String s, int start, Set<String> dict) {
if (start == s.length()) return true;
for (int end = start + 1; end <= s.length(); end++)
if (dict.contains(s.substring(start, end)) && can(s, end, dict)) return true;
return false;
}
}class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
return self.can(s, 0, set(wordDict))
def can(self, s: str, start: int, dict: Set[str]) -> bool:
if start == len(s):
return True
for end in range(start + 1, len(s) + 1):
if s[start:end] in dict and self.can(s, end, dict):
return True
return Falseclass Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> dict(wordDict.begin(), wordDict.end());
return can(s, 0, dict);
}
private:
bool can(const string& s, int start, unordered_set<string>& dict) {
if (start == (int)s.size()) return true;
for (int end = start + 1; end <= (int)s.size(); end++)
if (dict.count(s.substr(start, end - start)) && can(s, end, dict)) return true;
return false;
}
};function wordBreak(s, wordDict) {
function can(s, start, dict) {
if (start === s.length) return true;
for (let end = start + 1; end <= s.length; end++)
if (dict.has(s.substring(start, end)) && can(s, end, dict)) return true;
return false;
}
return can(s, 0, new Set(wordDict));
}2Optimal (1D DP over prefixes)
O(n · L²)L = longest word; each check builds a substring of length up to L.O(n)dp[0] = true. For each i, look back at split points j: if dp[j] is true and s[j..i) is in the set, dp[i] is true. Limiting j to the longest word length keeps it fast.
- dict = set; maxLen = longest word.
- For i in 1..n, for j from i - 1 down to max(0, i - maxLen): if dp[j] && dict has s[j..i), dp[i] = true; break.
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> dict = new HashSet<>(wordDict);
int maxLen = 0;
for (String w : wordDict) maxLen = Math.max(maxLen, w.length());
int n = s.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int i = 1; i <= n; i++)
for (int j = i - 1; j >= Math.max(0, i - maxLen); j--)
if (dp[j] && dict.contains(s.substring(j, i))) { dp[i] = true; break; }
return dp[n];
}
}class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dict = set(wordDict)
maxLen = 0
for w in wordDict:
maxLen = max(maxLen, len(w))
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
for i in range(1, n + 1):
for j in range(i - 1, max(0, i - maxLen) - 1, -1):
if dp[j] and s[j:i] in dict:
dp[i] = True
break
return dp[n]class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> dict(wordDict.begin(), wordDict.end());
int maxLen = 0;
for (const string& w : wordDict) maxLen = max(maxLen, (int)w.size());
int n = s.size();
vector<bool> dp(n + 1, false);
dp[0] = true;
for (int i = 1; i <= n; i++)
for (int j = i - 1; j >= max(0, i - maxLen); j--)
if (dp[j] && dict.count(s.substr(j, i - j))) { dp[i] = true; break; }
return dp[n];
}
};function wordBreak(s, wordDict) {
const dict = new Set(wordDict);
let maxLen = 0;
for (const w of wordDict) maxLen = Math.max(maxLen, w.length);
const n = s.length;
const dp = new Array(n + 1).fill(false);
dp[0] = true;
for (let i = 1; i <= n; i++)
for (let j = i - 1; j >= Math.max(0, i - maxLen); j--)
if (dp[j] && dict.has(s.substring(j, i))) { dp[i] = true; break; }
return dp[n];
}Edge cases to test
- Reusing the same word several times
- Many prefixes match but the suffix fails
Hints
Hint 1
dp[i] = can the first i characters be segmented? dp[i] is true if some dp[j] is true and s[j..i) is a word.
FAQ
What is the best time complexity for Word Break?
Optimal (1D DP over prefixes) runs in O(n · L²) time and O(n) extra space. L = longest word; each check builds a substring of length up to L.
Which pattern does Word Break use?
It is a dynamic programming problem that uses the 1d dp pattern. Other problems with the same pattern: Fibonacci Number, Climbing Stairs, Min Cost Climbing Stairs (2 jumps).
Is there a brute force solution for Word Break?
Yes. Recursion takes O(2ⁿ) time and O(n) space. Try every dictionary word as a prefix and recurse on the rest.
Which edge cases should I test for Word Break?
Reusing the same word several times; Many prefixes match but the suffix fails.