17. Word Break
mediumAsked at ByteDanceDecide 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 <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20
Examples
Example 1
s = "leetcode", wordDict = ["leet","code"]trueExample 2
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]falseApproaches
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.
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 →