Skip to main content

17. Word Break

mediumAsked at ByteDance

Decide whether a string can be segmented into dictionary words — ByteDance uses it to probe DP intuition before deeper text-segmentation pipeline questions.

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

Problem

Given a string s and a dictionary of words wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. The same dictionary word may be reused.

Constraints

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20

Examples

Example 1

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

Example 2

Input
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output
false

Approaches

1. Naive recursion

Try every prefix split recursively without memoization.

Time
O(2^n)
Space
O(n)
function go(i){ if(i===s.length) return true;
  for(const w of dict) if(s.startsWith(w,i)&&go(i+w.length)) return true;
  return false; }

Tradeoff:

2. Bottom-up DP

dp[i] = true means s[0..i) can be segmented. For each i, check all words ending at i.

Time
O(n * 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:

ByteDance-specific tips

ByteDance interviewers expect candidates to spell out the dp[i] meaning before coding, the same first move their NLP team makes when designing text-segmentation models.

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 ByteDance interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →