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: true
💡 Note: The string "applepenapple" can be segmented as "apple pen apple", where "apple" and "pen" are both in the dictionary. Note that "apple" is reused.
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 INPUT String s: l e e t c o d e 0 1 2 3 4 5 6 7 wordDict: "leet" "code" Input Values s = "leetcode" wordDict = ["leet", "code"] Length: 8 characters ALGORITHM STEPS 1 Create DP Array dp[i] = can segment s[0..i] 2 Initialize dp[0]=true Empty string is valid 3 For each position i Check all words in dict 4 Update dp[i] If dp[j] and s[j..i] in dict DP Table Progress: T F F F T F F F T 0 1 2 3 4 5 6 7 8 "leet" found at [0-4] "code" found at [4-8] Time: O(n*m*k) | Space: O(n) FINAL RESULT String can be segmented as: "leet" + "code" = "leetcode" Output: true [OK] Valid Segmentation dp[8] = true Key Insight: Dynamic Programming builds solutions bottom-up: dp[i] is true if we can segment s[0..i-1]. For each position i, check if any word in dictionary ends at i and dp[i - word.length] is true. This avoids exponential backtracking by storing intermediate results. TutorialsPoint - Word Break | Dynamic Programming Approach
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