Skip to main content

24. Word Break

mediumAsked at Notion

Determine if a string can be segmented into valid dictionary words using DP — Notion's rich-text parser uses the same bottom-up reachability logic to tokenize markdown spans and inline code without greedy backtracking.

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 wordDict can be reused multiple times.

Constraints

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • s and wordDict[i] consist of lowercase English letters only

Examples

Example 1

Input
s = "leetcode", wordDict = ["leet","code"]
Output
true

Explanation: "leetcode" = "leet" + "code".

Example 2

Input
s = "applepenapple", wordDict = ["apple","pen"]
Output
true

Explanation: "applepenapple" = "apple" + "pen" + "apple". Words can be reused.

Approaches

1. Recursive with memoization

Try all prefixes from index i; if the prefix is in the dict and the suffix is also breakable (cached), return true.

Time
O(n^2 * m)
Space
O(n)
function wordBreak(s, wordDict) {
  const dict = new Set(wordDict);
  const memo = new Map();
  function canBreak(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 (dict.has(s.slice(start, end)) && canBreak(end)) {
        memo.set(start, true);
        return true;
      }
    }
    memo.set(start, false);
    return false;
  }
  return canBreak(0);
}

Tradeoff:

2. Bottom-up DP

dp[i] = true if s[0..i) is breakable. For each position i, check all previous positions j where dp[j] is true and s[j..i) is in the dictionary.

Time
O(n^2)
Space
O(n + dict size)
function wordBreak(s, wordDict) {
  const dict = 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] && dict.has(s.slice(j, i))) {
        dp[i] = true;
        break;
      }
    }
  }
  return dp[s.length];
}

Tradeoff:

Notion-specific tips

Notion's markdown-to-block conversion must decide how to tokenize ambiguous inline spans — bold inside italic, code spans with backticks. They want to see you recognize this as a reachability DP rather than a greedy scan, and explain why greedy fails on overlapping prefixes.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Word Break and other Notion interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →