Word Break

Can s be segmented into dictionary words? 1D DP over prefixes.

Medium
Time O(n^2 * L) Space O(n)
LeetCode
3 min read
dp string

Problem#

Can s be segmented into a space-separated sequence of words from wordDict?

Examples#

  • s = "leetcode", wordDict = ["leet","code"]true
  • s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]false

Constraints#

  • 1 <= s.length <= 300.

Approach#

dp[i] = can s[0..i) be segmented. dp[0] = true. Transition: dp[i] = true iff some j < i has dp[j] && dict.contains(s[j..i)).

Solution#

Word Break
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> dict(wordDict.begin(), wordDict.end());
int n = s.size();
vector<bool> dp(n + 1, false);
dp[0] = true;
for (int i = 1; i <= n; ++i) {
for (int j = i - 1; j >= 0; --j) {
if (dp[j] && dict.count(s.substr(j, i - j))) { dp[i] = true; break; }
}
}
return dp[n];
}
};

Editorial#

DP marks every reachable prefix. Once dp[i] flips true, we break early. Hashing each candidate substring costs O(L) per lookup; tighter implementations bound i - j by max word length.

Complexity#

  • Time: O(n² * L).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.