Word Break - Problem
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note: The same word in the dictionary may be reused multiple times in the segmentation.
Input & Output
Example 1 — Basic Segmentation
$
Input:
s = "leetcode", wordDict = ["leet","code"]
›
Output:
true
💡 Note:
The string "leetcode" can be segmented as "leet code", where both "leet" and "code" are in the dictionary.
Example 2 — No Valid Segmentation
$
Input:
s = "applepenapple", wordDict = ["apple","pen"]
›
Output:
false
💡 Note:
The string cannot be segmented because "penapple" is not in the dictionary and cannot be further broken down using available words.
Example 3 — Multiple Valid Paths
$
Input:
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
›
Output:
false
💡 Note:
Even though "cats", "and", "dog" are all in dictionary, we cannot form "catsandog" because "sandog" cannot be segmented.
Constraints
- 1 ≤ s.length ≤ 300
- 1 ≤ wordDict.length ≤ 1000
- 1 ≤ wordDict[i].length ≤ 20
- 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 'leetcode' and dictionary ['leet', 'code']
2
Process
Find valid segmentations using dictionary words
3
Output
Return true if valid segmentation exists
Key Takeaway
🎯 Key Insight: Use dynamic programming to build valid segmentations incrementally by checking if each position can be reached from previous valid positions using dictionary words.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code