Algo-Sim › Dynamic Programming
Word Break
Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input
dp[i] is true when some reachable cut j leaves s[j..i) as a dictionary word. The arcs show successful and short candidates; counters include all checked substrings.
Problem
Given a string s and a list of words wordDict, return true if s can be split into a sequence of one or more dictionary words, with no letters left over. A word may be used more than once.
Constraints
- 1 ≤ s.length ≤ 300
- 1 ≤ wordDict.length ≤ 1000
- 1 ≤ wordDict[i].length ≤ 20
- All strings are lowercase; dictionary words are distinct
Edge cases to test
- Empty string:
true - A word reused many times
- Words that overlap but don’t tile
Follow-up questions
- How do you speed up the inner loop?
- Only try cuts up to the longest word length, or walk a trie of the words from each reachable start.
- How do you list every sentence?
- Backtrack with memoised suffix results (LC 140); the output can be exponential.
Solution
Java
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> words = new HashSet<>(wordDict);
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] && words.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}Python
def word_break(s, word_dict):
words = set(word_dict)
dp = [False] * (len(s) + 1)
dp[0] = True
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)]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool wordBreak(string &s, vector<string> &wordDict) {
unordered_set<string> words = unordered_set<string>(wordDict.begin(), wordDict.end());
vector<bool> dp = vector<bool>(int(s.size()) + 1);
dp[0] = true;
for (int i = 1; i <= int(s.size()); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && words.count(s.substr(j, (i) - (j)))) {
dp[i] = true;
break;
}
}
}
return dp[int(s.size())];
}
};
More Dynamic Programming problems
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)