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
Word Break II: Build All Valid SentencescatsanddogInput StringDictionarycatcatsandsanddogcats and dogcat sand dogSolution 1Solution 2Result: ["cats and dog", "cat sand dog"]
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
Asked in
Facebook 85 Google 72 Amazon 65 Microsoft 48
125.0K Views
High Frequency
~25 min Avg. Time
5.4K 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