Word Break is a classic dynamic programming problem that tests your ability to decompose strings efficiently.

You're given a string s and a dictionary of words wordDict. Your task is to determine if the entire string can be segmented into a sequence of dictionary words, where each word is separated by spaces.

Key Points:
• Words from the dictionary can be reused multiple times
• The entire string must be segmented (no leftover characters)
• Return true if segmentation is possible, false otherwise

Example: If s = "leetcode" and wordDict = ["leet", "code"], return true because "leetcode" can be segmented as "leet code".

Input & Output

example_1.py — 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.py — Word Reuse
$ Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
💡 Note: The string can be segmented as "apple pen apple". Note that "apple" is reused from the dictionary.
example_3.py — Impossible Segmentation
$ Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
💡 Note: No valid segmentation exists. While "cats", "and", "dog" are all in the dictionary, there's no way to segment "catsandog" completely.

Visualization

Tap to expand
Word Break VisualizationInput: "leetcode"Dict: ["leet", "code"]leetcodeDP Array Progress:TTT048"leet""code"✓ Complete segmentation found!
Understanding the Visualization
1
Setup
Convert dictionary to hash set and initialize DP array
2
Check Each Position
For each position, look back at all previous valid positions
3
Validate Substring
Check if substring from valid position to current forms a dictionary word
4
Mark Valid
If valid word found, mark current position as reachable
Key Takeaway
🎯 Key Insight: Use dynamic programming to avoid recomputing the same subproblems - if you can segment up to position i, you can extend to position j if there's a valid word from i to j.

Time & Space Complexity

Time Complexity
⏱️
O(n²)

We check every substring of s, and for each position we might check up to n previous positions

n
2n
Quadratic Growth
Space Complexity
O(n + m)

DP array of size n+1 plus hash set of size m (number of words in dictionary)

n
2n
Linearithmic Space

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
Asked in
Meta 45 Amazon 38 Google 32 Microsoft 28 Apple 22
52.5K Views
High Frequency
~18 min Avg. Time
1.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