16. Word Break
mediumAsked at ChimeDetermine if a string can be segmented into a space-separated sequence of dictionary words.
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 dictionary word may be reused multiple times.
Constraints
1 <= s.length <= 3001 <= wordDict.length <= 1000All strings consist of lowercase English letters.
Examples
Example 1
s = "leetcode", wordDict = ["leet","code"]trueExample 2
s = "applepenapple", wordDict = ["apple","pen"]trueApproaches
1. Naive recursion
Try every prefix that is in the dictionary and recurse on the suffix.
- Time
- O(2^n)
- Space
- O(n)
function can(s) {
if (s === '') return true;
for (const w of wordDict) {
if (s.startsWith(w) && can(s.slice(w.length))) return true;
}
return false;
}Tradeoff:
2. Bottom-up DP
Let dp[i] mean s[0..i) can be segmented. Transition: dp[i] = exists j < i where dp[j] is true and s[j..i) is in the dictionary set.
- Time
- O(n^2)
- 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:
Chime-specific tips
Chime treats word-break-style segmentation as a stand-in for parsing transaction memos in their fraud heuristics pipeline, so mention how memoization avoids re-scoring the same memo prefix.
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 Chime interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →