Dictionary Word Segmentation - Problem

Given a string s and a dictionary of words wordDict, find all possible ways to segment the string into valid dictionary words.

Return a list of all possible segmentations where each segmentation is a space-separated string of dictionary words.

Example:

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

Output: ["cats and dog", "cat sand dog"]

The string can be segmented as "cats and dog" or "cat sand dog".

Input & Output

Example 1 — Multiple Valid Segmentations
$ Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
Output: ["cats and dog", "cat sand dog"]
💡 Note: Two valid ways: "cats" + "and" + "dog" or "cat" + "sand" + "dog". Both use only dictionary words.
Example 2 — Single 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 segmentations exist using different combinations of dictionary words.
Example 3 — No Valid Segmentation
$ Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: []
💡 Note: No way to segment the string using only dictionary words - 'andog' is not valid.

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
INPUTALGORITHMRESULT"catsanddog"Dictionary:"cat""cats""and""sand""dog"1Try all possible splits2Check if prefix is valid word3Recursively solve suffix4Use memoization to cacheExample Splits:"cats" + "and" + "dog" ✓"cat" + "sand" + "dog" ✓Valid Segmentations:"cats and dog""cat sand dog"Key Insight:Use memoization to cache subproblem results - each substring segmentation is computed only once, avoiding exponential redundant work.TutorialsPoint - Dictionary Word Segmentation | Memoized Recursion
Asked in
Google 45 Facebook 38 Amazon 42 Microsoft 35
78.0K Views
High Frequency
~25 min Avg. Time
1.9K 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