Skip to main content

22. Word Break

mediumAsked at Chegg

Determine if a string can be segmented into dictionary words — Chegg uses this DP pattern for tokenizing educational query strings and segmenting compound subject names.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

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. The same word in the dictionary may be reused multiple times.

Constraints

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • s and wordDict[i] consist of only lowercase English letters
  • All strings in wordDict are unique

Examples

Example 1

Input
s = "leetcode", wordDict = ["leet","code"]
Output
true

Example 2

Input
s = "applepenapple", wordDict = ["apple","pen"]
Output
true

Approaches

1. Recursive backtracking (naive)

Try every prefix at each position; exponential without memoization due to overlapping subproblems.

Time
O(2^n)
Space
O(n)
function wordBreak(s, wordDict) {
  const set = new Set(wordDict);
  function bt(start) {
    if (start === s.length) return true;
    for (let end = start + 1; end <= s.length; end++)
      if (set.has(s.slice(start, end)) && bt(end)) return true;
    return false;
  }
  return bt(0);
}

Tradeoff:

2. Bottom-up DP

dp[i] = true if s[0..i-1] can be segmented; for each i, check all j < i where dp[j] is true and s[j..i] is in the dictionary.

Time
O(n^2 * m)
Space
O(n)
function wordBreak(s, wordDict) {
  const set = 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] && set.has(s.slice(j, i))) { dp[i] = true; break; }
  return dp[s.length];
}

Tradeoff:

Chegg-specific tips

Chegg favors the DP approach here and expects you to preload wordDict into a Set for O(1) lookup — they may follow up asking how to reconstruct all valid segmentations.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Word Break and other Chegg interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →