21. Word Break
mediumAsked at BrexDetermine whether a string can be segmented into dictionary words — a DP string problem Brex applies to category-keyword parsing in its rules engine.
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.
Constraints
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20wordDict contains distinct strings
Examples
Example 1
s = "leetcode", wordDict = ["leet","code"]trueExample 2
s = "applepenapple", wordDict = ["apple","pen"]trueApproaches
1. Naive recursion
Try every prefix; if it is in the dict recurse on the suffix. Exponential without memoization.
- Time
- O(2^n)
- Space
- O(n)
function wb(s, dict) {
if (!s.length) return true;
for (let i = 1; i <= s.length; i++)
if (dict.includes(s.slice(0,i)) && wb(s.slice(i), dict)) return true;
return false;
}Tradeoff:
2. Bottom-up DP with set lookup
dp[i] is true if s[0..i-1] can be segmented. For each position j <= i check if dp[j] is true and s[j..i-1] is in the word set. Runs in O(n^2) with O(1) set lookups.
- Time
- O(n^2)
- Space
- O(n + dict size)
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:
Brex-specific tips
Brex asks about fintech infrastructure, multi-currency handling, and spend management algorithms. Expect LeetCode-style DSA focused on hash maps, sorting, and dynamic programming.
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 Brex interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →