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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code