139. Word Break
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks whether a given string s can be segmented into a sequence of one or more words from a provided dictionary wordDict. Words from the dictionary can be reused. This is a classic string segmentation problem that can be efficiently solved using dynamic programming.
Solution
Word Break in Python
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
# Convert wordDict to a set for efficient lookups.
word_set = set(wordDict)
n = len(s)
# dp[i] will be True if the prefix s[:i] can be segmented.
dp = [False] * (n + 1)
# Base case: an empty string can be segmented.
dp[0] = True
# Get max word length for optimization.
max_len = 0
if not wordDict:
return False
for word in wordDict:
max_len = max(max_len, len(word))
# Iterate through the string to fill the DP table.
for i in range(1, n + 1):
# Check for possible splits ending at i.
# We only need to check back max_len characters.
for j in range(i - 1, -1, -1):
# Optimization: if the substring is longer than any word in dict, skip.
if i - j > max_len:
break
# If s[:j] can be segmented and s[j:i] is a word in the dictionary,
# then s[:i] can also be segmented.
if dp[j] and s[j:i] in word_set:
dp[i] = True
break # Found a valid segmentation for s[:i], move to the next i.
# The result is whether the entire string s (s[:n]) can be segmented.
return dp[n]
Word Break in Java
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
// Convert wordDict to a hash set for O(1) average time complexity checks.
Set<String> wordSet = new HashSet<>(wordDict);
int n = s.length();
// Find the maximum length of a word in the dictionary for optimization.
int maxLen = 0;
for (String word : wordDict) {
maxLen = Math.max(maxLen, word.length());
}
// dp[i] is true if the prefix of s of length i (s.substring(0, i)) can be segmented.
boolean[] dp = new boolean[n + 1];
// Base case: an empty string can be segmented.
dp[0] = true;
// Iterate through each position in the string.
for (int i = 1; i <= n; i++) {
// Check all possible last words ending at index i-1.
// We only need to check substrings of length up to maxLen.
for (int j = i - 1; j >= 0; j--) {
if (i - j > maxLen) {
break; // Optimization
}
// If s[0...j-1] is breakable (dp[j] is true) and
// the substring s[j...i-1] is in the dictionary,
// then s[0...i-1] is breakable.
if (dp[j]) {
String sub = s.substring(j, i);
if (wordSet.contains(sub)) {
dp[i] = true;
break; // Found a way to segment up to i, so break to check next i.
}
}
}
}
// The final result is in dp[n], which corresponds to the whole string.
return dp[n];
}
}
Word Break in C++
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
// Convert wordDict to a hash set for efficient lookup.
unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
int n = s.length();
// dp[i] will be true if s[0...i-1] can be segmented.
vector<bool> dp(n + 1, false);
// Base case: an empty string can always be segmented.
dp[0] = true;
// Find the maximum length of a word in the dictionary for optimization.
int maxLen = 0;
for (const string& word : wordDict) {
maxLen = max(maxLen, (int)word.length());
}
// Iterate through the string to fill the DP table.
for (int i = 1; i <= n; ++i) {
// Check all possible last words ending at index i-1.
// We only need to check substrings of length up to maxLen.
for (int j = i - 1; j >= 0; --j) {
if (i - j > maxLen) {
break; // Optimization: substring is too long.
}
// If s[0...j-1] is breakable (dp[j] is true)
// and the substring s[j...i-1] is in the dictionary,
// then s[0...i-1] is also breakable.
if (dp[j]) {
string sub = s.substr(j, i - j);
if (wordSet.count(sub)) {
dp[i] = true;
break; // Found a valid segmentation, move to the next i.
}
}
}
}
// The result is whether the entire string s (s[0...n-1]) can be segmented.
return dp[n];
}
};
Word Break in TypeScript
function wordBreak(s: string, wordDict: string[]): boolean {
// Convert wordDict to a Set for efficient lookups.
const wordSet = new Set(wordDict);
const n = s.length;
// Find the maximum length of a word in the dictionary for optimization.
let maxLen = 0;
for (const word of wordDict) {
maxLen = Math.max(maxLen, word.length);
}
// dp[i] will be true if the prefix of s of length i (s.substring(0, i)) can be segmented.
const dp = new Array(n + 1).fill(false);
// Base case: an empty string can always be segmented.
dp[0] = true;
// Iterate through the string to fill the DP table.
for (let i = 1; i <= n; i++) {
// Check all possible last words ending at index i-1.
// We only need to check substrings of length up to maxLen.
for (let j = i - 1; j >= 0; j--) {
if (i - j > maxLen) {
break; // Optimization
}
// If s[0...j-1] is breakable (dp[j] is true) and
// the substring s[j...i-1] is in the dictionary,
// then s[0...i-1] is breakable.
if (dp[j]) {
const sub = s.substring(j, i);
if (wordSet.has(sub)) {
dp[i] = true;
break; // Found a valid segmentation, move to the next i.
}
}
}
}
// The result is whether the entire string s (s[0...n-1]) can be segmented.
return dp[n];
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.