Word Break II - Problem
Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Input & Output
Example 1 — Basic Segmentation
$
Input:
s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
›
Output:
["cats and dog","cat sand dog"]
💡 Note:
Two valid ways: 'cats' + 'and' + 'dog' = 'cats and dog', and 'cat' + 'sand' + 'dog' = 'cat sand dog'
Example 2 — No Valid Segmentation
$
Input:
s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
›
Output:
["pine apple pen apple","pineapple pen apple","pine applepen apple"]
💡 Note:
Multiple valid combinations using different word splits
Example 3 — Single Word
$
Input:
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
›
Output:
[]
💡 Note:
No valid segmentation possible - 'andog' cannot be formed from dictionary words
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 strings in wordDict are unique
Visualization
Tap to expand
Understanding the Visualization
1
Input
String 'catsanddog' and dictionary ['cat','cats','and','sand','dog']
2
Process
Find all ways to split string using dictionary words
3
Output
All valid sentences: ['cats and dog', 'cat sand dog']
Key Takeaway
🎯 Key Insight: Use backtracking with memoization to efficiently generate all valid sentence combinations while avoiding redundant calculations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code