20. Word Break
mediumAsked at InstacartDetermine if a string can be segmented using a dictionary — Instacart applies this DP pattern when parsing user-typed grocery queries that contain concatenated product tokens against the catalog word list.
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 the words in wordDict consist of only lowercase English lettersAll the strings of wordDict are unique
Examples
Example 1
s = "leetcode", wordDict = ["leet","code"]trueExplanation: "leetcode" can be segmented as "leet code".
Example 2
s = "applepenapple", wordDict = ["apple","pen"]trueApproaches
1. Recursive with memoization
Try all prefix splits from the current index. If a prefix is in the dictionary and the suffix can also be segmented (memoized), return true.
- Time
- O(n^2 * m)
- Space
- O(n)
function wordBreak(s, wordDict) {
const wordSet = new Set(wordDict);
const memo = new Map();
function dp(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 (wordSet.has(s.slice(start, end)) && dp(end)) {
memo.set(start, true);
return true;
}
}
memo.set(start, false);
return false;
}
return dp(0);
}Tradeoff:
2. Bottom-up DP
dp[i] = true if s[0..i) can be segmented. For each position i, check all j < i where dp[j] is true and s[j..i) is in the dictionary.
- Time
- O(n^2)
- Space
- O(n)
function wordBreak(s, wordDict) {
const wordSet = 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] && wordSet.has(s.slice(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length];
}Tradeoff:
Instacart-specific tips
Instacart's search team parses concatenated product strings against a large SKU dictionary — the interviewer wants to see you build the DP table iteratively rather than recurse, and confirm you understand that a Set lookup on the substring is O(word length), not O(1), so the true complexity depends on average word length.
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 Instacart interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →