Algorithm Day87 - Word Break
🧩 Problem Description
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.
You may assume the dictionary does not contain duplicate words.
💬 Examples
Example 1
1 | Input: s = "leetcode", wordDict = ["leet","code"] |
Example 2
1 | Input: s = "applepenapple", wordDict = ["apple","pen"] |
Example 3
1 | Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] |
💡 Intuition
We want to determine whether s can be split into valid words from wordDict. Two common approaches:
Dynamic Programming (DP): Let
dp[i]betrueifs[0..i)can be segmented. For eachi, check all possible previous cutsj < iand ifdp[j]is true ands[j..i)is inwordDict, setdp[i] = true.BFS / Trie: Treat positions as nodes and edges when substring is a word; run BFS from position 0 to
nto avoid redundant work.
DP is simple and efficient when implemented with a hash set for dictionary lookups and pruning via max word length.
🔢 Java Code (DP)
1 | import java.util.*; |
⏱ Complexity Analysis
- Time: O(n * L) where
n= length ofs,L= max word length; substring/hash lookups average O(1). - Space: O(n) for DP array + O(m) for dictionary storage.
✍️ Summary
- DP with dictionary lookup and max-word-length optimization is the standard solution.
- BFS is an alternative that often performs well with proper visited pruning.
Related problems: lc-140 (Word Break II), lc-472 (Concatenated Words).