26. Word Break
mediumAsked at BookingDetermine if a string can be segmented using a dictionary of valid words — Booking's NLP pipeline applies the same DP-based segmentation when parsing free-text destination queries into canonical city and region tokens.
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. Words in the dictionary may be reused.
Constraints
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20s and wordDict[i] consist of lowercase English lettersAll strings in wordDict are unique
Examples
Example 1
s = "leetcode", wordDict = ["leet","code"]trueExplanation: "leet" + "code" = "leetcode".
Example 2
s = "applepenapple", wordDict = ["apple","pen"]trueExample 3
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]falseApproaches
1. Recursive with memoization
Try every word at the current position; if it matches and the remainder also succeeds, return true. Cache results by index.
- 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, check all words that end at i.
- Time
- O(n^2 * m)
- 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:
Booking-specific tips
Booking processes queries in 43 languages — they appreciate candidates who mention that the word-set approach generalises to multi-language dictionaries and ask how you'd handle overlapping word boundaries (the DP handles it naturally).
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 Booking interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →