Word Break
Medium
Dynamic ProgrammingString
Problem
Given a string s and a dictionary of words, return true iff s can be segmented into a space-separated sequence of dictionary words. Each word can be used multiple times.
Example 1
Input: s = "leetcode", dict = ["leet","code"]
Output: true
Example 2
Input: s = "applepenapple", dict = ["apple","pen"]
Output: true
Example 3
Input: s = "catsandog", dict = ["cats","dog","sand","and","cat"]
Output: false
Constraints
- 1 ≤ s.length ≤ 300
- 1 ≤ dict.length ≤ 1000
Approach — Dynamic Programming
This is a Dynamic Programming problem. The idea: break the problem into overlapping subproblems and build the answer up, caching results so nothing is recomputed. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) to O(n²) time.
Solution code
Python
class Solution:
def wordBreak(self, s, dict):
words = set(dict)
n = len(s)
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]
Java
import java.util.*;
class Solution {
public boolean wordBreak(String s, List<String> dict) {
Set<String> set = new HashSet<>(dict);
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && set.contains(s.substring(j, i))) { dp[i] = true; break; }
}
}
return dp[s.length()];
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Word Break interactively → ← All solutions