๐Ÿ—“๏ธ Day 36: Word Break II โ€” Return All Segmentations

๐Ÿง  Concept Deep Dive

Today we extend the Word Break problem to not just check if a word can be broken โ€” but to return all possible segmentations.

Given s and wordDict, return all ways to break s into valid words.

We'll use recursion with memoization, and instead of returning booleans, we return arrays of sentences from each index.


๐ŸŽฏ Visual Intuition

Imagine this:

s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]

We want to find all sentences:

  • "cats and dog"
  • "cat sand dog"

Break from index 0:

"catsanddog"
โ”œโ”€ "cat" โœ” โ†’ recurse on "sanddog"
โ”‚                 โ”œโ”€ "sand" โœ” โ†’ recurse on "dog"
โ”‚                 โ”‚             โ””โ”€ "dog" โœ” โœ…
โ”œโ”€ "cats" โœ” โ†’ recurse on "anddog"
โ”‚                  โ””โ”€ "and" โœ” โ†’ "dog" โœ” โœ…

Each path forms a full sentence.


๐Ÿ› ๏ธ Key Patterns

๐Ÿ’ก DFS + Memoization Returning Arrays

function wordBreak(s: string, wordDict: string[]): string[] {
  const wordSet = new Set(wordDict);
  const memo: Record<number, string[]> = {};

  const dfs = (start: number): string[] => {
    if (start === s.length) return [""];
    if (start in memo) return memo[start];

    const result: string[] = [];
    for (let end = start + 1; end <= s.length; end++) {
      const word = s.slice(start, end);
      if (wordSet.has(word)) {
        for (const sub of dfs(end)) {
          result.push(word + (sub ? " " + sub : ""));
        }
      }
    }
    return (memo[start] = result);
  };

  return dfs(0);
}

๐Ÿ“˜ Example

Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
Output:
[
  "cats and dog",
  "cat sand dog"
]
Input: s = "pineapplepenapple", wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]

๐Ÿงช Homework

  1. Modify the function to return the number of possible segmentations.
  2. Try a version without memoization and compare performance.
  3. What if wordDict contains empty string? Should you handle that case?

๐Ÿง  Big-O Cheat Sheet

  • Time: O(2^n) worst case (exponential paths), but much faster with memoization
  • Space: O(n * k) โ€” where k is the average number of splits from an index

๐Ÿ”ฎ Up Next

โ–ถ๏ธ Day 37: Decode Ways โ€” DP on Strings with Numbers

This page was last edited on 2025-08-01 10:13

Powered by Wiki|Docs

This page was last edited on 2025-08-01 10:13

Tri Nguyen
No Copyright

Powered by Wiki|Docs