Word Break
Medium
Topics
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. A word may be reused.
Example 1
s
dict
one wordthe next
The shading cuts the string into
leet + code, every piece a dictionary word, so the answer is true. Words may be reused and need not all be used, and the pieces must cover the string with no gap or overlap.The string with its word boundaries shaded, and the dictionary below.
Input: s = "leetcode", wordDict = ["leet","code"] Output: true
Example 2
s
dict
No way of cutting
catsandog leaves every piece in the dictionary, so the answer is false. Words may be reused and need not all be used, but the pieces must cover the whole string — getting most of the way does not count.Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output: false
Constraints
- 1 <= s.length <= 300
- 1 <= wordDict.length <= 1000
- All dictionary words are unique.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Define dp[i] = "the first i characters can be segmented." A prefix is breakable if some earlier breakable point j exists and s[j:i] is a dictionary word.
Approach
- Put the dictionary in a set for O(1) lookups.
- dp[0] = true (empty prefix).
- For each end i, if any dp[j] is true and s[j:i] is in the set, set dp[i] = true.
- Return dp[n].
Dry Run
s = "catsandog" dict = {cats, dog, sand, and, cat}
dp[i] = "the first i characters can be segmented". dp[0] = true, the empty prefix.
i=1 "c" no j works dp[1] = false
i=2 "ca" no j works dp[2] = false
i=3 "cat" dp[0] and "cat" dp[3] = true
i=4 "cats" dp[0] and "cats" dp[4] = true
i=5 "catsa" no j works dp[5] = false
i=6 "catsan" no j works dp[6] = false
i=7 "catsand" dp[3] and "sand" dp[7] = true
i=8 "catsando" no j works dp[8] = false
i=9 "catsandog" no j works dp[9] = false
answer false
Look at i=7. It is reachable through dp[3], which means "cat" + "sand" -- not
through dp[4] and "and", because dp[4] is "cats" and that would leave "and" to
start at index 4, which it does not. The table is consulted, not the string: the
only question at each i is whether SOME earlier true position is a word away.
That is why dp[j] has to be read rather than just testing j == 0. Requiring every
word to start at position 0 asks whether the whole string is one dictionary word,
so "leetcode" with {leet, code} would come back false.
The interesting part of this input is that it reaches i=7 with three different
true positions behind it and still fails. "catsand" segments fine; "og" is not a
word and nothing reaches 9.
Greedy does not substitute for the table, though this input does not show it --
a longest-match-first walk also returns false here, for its own reasons. The
shape that separates them is "aaaa" against {aaa, aa}: greedy takes "aaa", is
left with a single "a", and gives up, while the DP finds "aa" + "aa". Every
earlier true position stays available to the DP, which is the part greedy throws
away.
The inner break is an optimisation and not logic. This is reachability, not a
count, so one route to i is as good as five.Complexity
- Time — O(n^2 * L): for each end, scan all starts and hash a substring of length up to L.
- Space — O(n): the dp array plus the word set.
Common Pitfalls
dp[j]has to be consulted, not justj == 0. Requiring the prefix to start at 0 asks whether the whole string is a single word, so any input needing two or more words returns false.- The inner
breakis an optimisation, not logic -- one way to reachiis enough, since this is reachability rather than a count.
Full Solution — all languages
class Solution:
def wordBreak(self, s, wordDict):
wset=set(wordDict)
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 wset:
dp[i]=True
break
return dp[-1]import java.util.*;
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> w=new HashSet<>(wordDict);
int n=s.length();
boolean[] dp=new boolean[n+1];
dp[0]=true;
for(int i=1;i<=n;i++)for(int j=0;j<i;j++)if(dp[j]&&w.contains(s.substring(j,i))) {
dp[i]=true;
break;
}
return dp[n];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool wordBreak(string s, vector<string>& wordDict) {
set<string> w(wordDict.begin(),wordDict.end());
int n=s.size();
vector<char> dp(n+1,0);
dp[0]=1;
for(int i=1;i<=n;i++)for(int j=0;j<i;j++)if(dp[j]&&w.count(s.substr(j,i-j))) {
dp[i]=1;
break;
}
return dp[n];
}
};/**
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/ var wordBreak = function(s, wordDict) {
const wset=new Set(wordDict);
const dp=new Array(s.length+1).fill(false);
dp[0]=true;
for(let i=1;i<=s.length;i++) {
for(let j=0;j<i;j++) {
if(dp[j]&&wset.has(s.slice(j,i))) {
dp[i]=true;
break;
}
}
}
return dp[s.length];
};