sagelearnai

Word Break

Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #139

Return true if s can be split into a sequence of one or more words from wordDict. Dictionary words may be reused.

Examples

text
s = "applepenapple", wordDict = ["apple", "pen"]   →  true
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]  →  false
s = "aaaaaaa", wordDict = ["aaa", "aaaa"]          →  true   (aaa + aaaa)

Hints

  1. dp[i] = can the prefix s[:i] be segmented?
  2. dp[i] is true if some earlier split point j has dp[j] true and s[j:i] is a word.
  3. Only check j values within the longest dictionary word length.

Approach

State: dp[i] = whether s[:i] can be segmented. Base: dp[0] = True (the empty prefix). For each end i, check split points j with i − j ≤ maxLen: if dp[j] and s[j:i] is in the word set, then dp[i] = True. The answer is dp[n]. Using a set for the dictionary and the max word length keeps it fast.

Complexity

Time: O(n · L²) for max word length L (slicing costs O(L)). Space: O(n).

Python solution
def wordBreak(s, wordDict):
    words = set(wordDict)
    max_len = max(map(len, words)) if words else 0
    dp = [True] + [False] * len(s)
    for i in range(1, len(s) + 1):
        for j in range(max(0, i - max_len), i):
            if dp[j] and s[j:i] in words:
                dp[i] = True
                break
    return dp[len(s)]
JavaScript solution
function wordBreak(s, wordDict) {
  const words = new Set(wordDict);
  const maxLen = Math.max(0, ...wordDict.map((w) => w.length));
  const dp = new Array(s.length + 1).fill(false); dp[0] = true;
  for (let i = 1; i <= s.length; i++) {
    for (let j = Math.max(0, i - maxLen); j < i; j++) {
      if (dp[j] && words.has(s.slice(j, i))) { dp[i] = true; break; }
    }
  }
  return dp[s.length];
}