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 - Dynamic Programming with Backtracking INPUT String s: "catsanddog" c a t s a n d d o g 0 1 2 3 4 5 6 7 8 9 wordDict: cat cats and sand dog Possible Segmentations: catsanddog cat cats sand and dog dog ALGORITHM STEPS 1 Build Word Set Convert wordDict to HashSet for O(1) lookup 2 Memoization Map Cache results for each starting index 3 Recursive DFS Try all prefixes, if in dict recurse on suffix 4 Backtrack Combine word with all suffix sentences Memo Cache Example: memo[7] = ["dog"] memo[4] = ["and dog"] memo[3] = ["sand dog"] memo[0] = ["cats and dog", "cat sand dog"] FINAL RESULT All Valid Sentences: "cats and dog" cats and dog "cat sand dog" cat sand dog Output Array: ["cats and dog", "cat sand dog"] OK - 2 Solutions Time: O(n * 2^n) Space: O(n * 2^n) Key Insight: Use DFS with memoization to avoid recomputing results for the same suffix. For each position, try all possible word matches and recursively solve for the remaining string. Store computed sentences for each index to prune redundant work. This converts exponential redundancy into polynomial. TutorialsPoint - Word Break II | DP + Backtracking Approach
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