Word Break II: Sentence Reconstruction Challenge

Imagine you have a string of characters with no spaces and a dictionary of valid words. Your mission is to add spaces strategically to transform this string into meaningful sentences where every word exists in your dictionary.

๐ŸŽฏ Goal: Find all possible ways to break the string into valid dictionary words
๐Ÿ“ Input: A string s and an array wordDict of dictionary words
๐ŸŽ Output: All possible sentences formed by adding spaces

Example: Given s = "catsanddog" and wordDict = ["cat", "cats", "and", "sand", "dog"], you could form:
โ€ข "cats and dog"
โ€ข "cat sand dog"

Note: Dictionary words can be reused multiple times in different combinations!

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "catsanddog", wordDict = ["cat", "cats", "and", "sand", "dog"]
โ€บ Output: ["cats and dog", "cat sand dog"]
๐Ÿ’ก Note: Both "cats and dog" and "cat sand dog" are valid sentences. "cats" + "and" + "dog" and "cat" + "sand" + "dog" are both valid word combinations.
example_2.py โ€” Multiple Solutions
$ Input: s = "pineapplepenapple", wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
โ€บ Output: ["pine apple pen apple", "pineapple pen apple", "pine applepen apple"]
๐Ÿ’ก Note: Three different ways to break the string: using "pine apple", "pineapple", or "pine applepen" at the beginning.
example_3.py โ€” No Solution
$ Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
โ€บ Output: []
๐Ÿ’ก Note: No valid way to break "catsandog" using the given dictionary words. "sandog" is not breakable into valid words.

Visualization

Tap to expand
Word Break II: Complete VisualizationInput: s = "catsanddog", wordDict = ["cat", "cats", "and", "sand", "dog"]String breakdown visualization:catsanddog"cat""s" or"sand""and""dog"Solution Tree (Memoized):0solve("catsanddog")3"cat" + solve("sanddog")4"cats" + solve("anddog")โ†“ cached result: ["sand dog"]โ†’ ["cat sand dog"]โ†“ cached result: ["and dog"]โ†’ ["cats and dog"]Memoization Cache:Position | Substring | Cached Solutions0 | "catsanddog" | ["cats and dog", "cat sand dog"]3 | "sanddog" | ["sand dog"] โœ“4 | "anddog" | ["and dog"] โœ“7 | "dog" | ["dog"] โœ“10 | "" | [""] (base case)Final Result: ["cats and dog", "cat sand dog"]โœ“ Both sentences use only dictionary wordsโœ“ Memoization eliminated redundant substring calculations
Understanding the Visualization
1
Setup
Convert dictionary to hash set for O(1) lookup. Initialize memoization cache.
2
Try First Word
At each position, try all possible words that start from current position.
3
Recursively Solve
For each valid word found, recursively solve for the remaining substring.
4
Cache Results
Store results for each starting position to avoid redundant calculations.
5
Combine Solutions
Combine current word with all solutions from remaining string to build final sentences.
Key Takeaway
๐ŸŽฏ Key Insight: Memoization transforms an exponential problem into a manageable one by caching substring solutions, making Word Break II efficient even with multiple valid combinations!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ + 2^n)

O(nยฒ) to check all substrings, plus O(2^n) for generating all possible combinations in worst case

n
2n
โš  Quadratic Growth
Space Complexity
O(nยฒ + 2^n)

O(nยฒ) for memoization table plus O(2^n) for storing all possible sentences

n
2n
โš  Quadratic Space

Constraints

  • 1 โ‰ค s.length โ‰ค 20
  • 1 โ‰ค wordDict.length โ‰ค 1000
  • 1 โ‰ค wordDict[i].length โ‰ค 10
  • s and wordDict[i] consist of only lowercase English letters
  • All the strings of wordDict are unique
  • Input is guaranteed to be valid according to the problem's requirements
Asked in
Google 67 Amazon 45 Facebook 38 Microsoft 29 Apple 22
95.4K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen