74. Word Break
Return true if s can be split into a sequence of one or more words from wordDict. Words may be reused.
Example 1
Input:
s = "pineapplepen", wordDict = ["apple","pen","applepen","pine","pineapple"]Output:
trueExample 2
Input:
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]Output:
falseHint 1
dp[i] is true if some split point j < i has dp[j] true and s[j:i] is a word.
Approach 1: Plain recursion
Try every prefix word; exponential without memo.
⏱ Time O(2ⁿ)💾 Space O(n)
Approach 2: Bottom-up DP ✅
dp over prefix lengths.
⏱ Time O(n² · L)💾 Space O(n)
Reference solution for Bottom-up DP (time O(n² · L), space O(n)). Each solution passes every test in all four languages.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
words = set(wordDict)
dp = [True] + [False] * len(s) # dp[i]: s[:i] can be segmented
for i in range(1, len(s) + 1):
for j in range(i):
if dp[j] and s[j:i] in words:
dp[i] = True
break
return dp[len(s)]class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> words = new HashSet<>(wordDict);
boolean[] dp = new boolean[s.length() + 1]; // dp[i]: s[0..i) can be segmented
dp[0] = true;
for (int i = 1; i <= s.length(); i++)
for (int j = 0; j < i; j++)
if (dp[j] && words.contains(s.substring(j, i))) { dp[i] = true; break; }
return dp[s.length()];
}
}class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> words(wordDict.begin(), wordDict.end());
vector<bool> dp(s.size() + 1, false); // dp[i]: s[0..i) can be segmented
dp[0] = true;
for (size_t i = 1; i <= s.size(); i++)
for (size_t j = 0; j < i; j++)
if (dp[j] && words.count(s.substr(j, i - j))) { dp[i] = true; break; }
return dp[s.size()];
}
};function wordBreak(s, wordDict) {
const words = new Set(wordDict), dp = new Array(s.length + 1).fill(false); // dp[i]: s[0..i) can be segmented
dp[0] = true;
for (let i = 1; i <= s.length; i++)
for (let j = 0; j < i; j++)
if (dp[j] && words.has(s.slice(j, i))) { dp[i] = true; break; }
return dp[s.length];
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
This problem is explained in the lesson Dynamic Programming (1-D).
Run your code to see results here.