22. Word Break
mediumAsked at CoupangDecide whether a string can be segmented into dictionary words, mirroring how Coupang's Korean e-commerce search ranking segments user queries against an in-memory product-name lexicon.
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 dictionary words. Words can 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="applepenapple", wordDict=["apple","pen"]trueApproaches
1. Recursion
Try every prefix and recurse on the remainder.
- Time
- O(2^n)
- Space
- O(n)
function dfs(s) {
if (s.length === 0) return true;
for (const w of wordDict)
if (s.startsWith(w) && dfs(s.slice(w.length))) return true;
return false;
}Tradeoff:
2. Bottom-up DP
dp[i] = can prefix of length i be segmented. dp[i] is true if some j < i has dp[j] true and s[j..i] in dict.
- 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:
Coupang-specific tips
Coupang's Korean e-commerce search ranking segments user queries against an in-memory lexicon under tight latency; DP with a hashed lexicon is the canonical pattern for sub-millisecond segmentation.
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 Coupang interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →