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
Word Break Problem OverviewInput String:leetcodeDictionary:leetcodeSegmentation Process:leet+code✓ in dict✓ in dictResult: trueValid segmentation found!
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.
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
89.2K Views
High Frequency
~25 min Avg. Time
2.8K 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