29. Word Break
mediumAsked at BoxDetermine if a string can be segmented using a dictionary of valid tokens — Box applies the same DP to validate that composite file paths and auto-generated document slugs can be decomposed into recognized folder and tag components.
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 <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20s and wordDict[i] consist of only lowercase English lettersAll strings in wordDict are unique
Examples
Example 1
s = "leetcode", wordDict = ["leet","code"]trueExample 2
s = "applepenapple", wordDict = ["apple","pen"]trueExplanation: "apple", "pen", "apple" — the word "apple" is reused.
Approaches
1. Brute force — recursion with memoization
Try every prefix of s; if the prefix is in the dictionary, recurse on the remainder. Memoize results by start index to avoid re-computation.
- Time
- O(n^2 * m) where m = avg word length
- Space
- O(n)
function wordBreak(s, wordDict) {
const set = new Set(wordDict);
const memo = new Map();
function dfs(start) {
if (start === s.length) return true;
if (memo.has(start)) return memo.get(start);
for (let end = start + 1; end <= s.length; end++) {
if (set.has(s.slice(start, end)) && dfs(end)) {
memo.set(start, true);
return true;
}
}
memo.set(start, false);
return false;
}
return dfs(0);
}Tradeoff:
2. Optimal — bottom-up DP
dp[i] = true if s[0..i-1] can be segmented. For each position i, check every j < i: if dp[j] is true and s[j..i] is in the dictionary, set dp[i] = true.
- Time
- O(n^2)
- Space
- O(n)
function wordBreak(s, wordDict) {
const set = new Set(wordDict);
const n = s.length;
const dp = new Array(n + 1).fill(false);
dp[0] = true;
for (let i = 1; i <= n; i++) {
for (let j = 0; j < i; j++) {
if (dp[j] && set.has(s.slice(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[n];
}Tradeoff:
Box-specific tips
Box often extends this to 'Word Break II' (LC 140) — returning all valid segmentations — which is a direct proxy for their tag-suggestion engine that decomposes document names into all valid keyword sequences. Practice tracing the dp array values out loud; Box interviewers reward candidates who can articulate why dp[0] = true anchors the entire recurrence.
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 Box interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →