Coding Interview PatternsWord Break
MediumTrie
Word Break
Explanation & Solution
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.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Use a trie combined with dynamic programming to solve this problem efficiently.
Input:s = "leetcode", wordDict = ["leet","code"]
0
leet
1
code
Output: true
Explanation: "leetcode" can be segmented as "leet code".
Constraints
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20sandwordDict[i]consist of only lowercase English letters- All the strings of
wordDictare unique
Approach
Trie pattern
1. Build a Trie from the Dictionary
- Create a TrieNode class with
childrenand anisEndflag - Insert every word from
wordDictinto the trie character by character - Mark the last node of each word with
isEnd = true
2. Initialize DP Array
- Create a boolean array
dpof sizen + 1(wherenis the length ofs) dp[i]means the substrings[0..i-1]can be segmented into dictionary words- Set
dp[0] = true(empty string is always valid)
3. Fill DP Using Trie Lookups
- For each index
iwheredp[i]istrue: - Start traversing the trie from the root, matching characters
s[i], s[i+1], ... - If at any point the trie character is missing,
break(no dictionary word starts this way) - If we reach a node with
isEnd = true, setdp[j + 1] = true(we found a valid word from indexitoj) - Continue matching to find longer dictionary words starting at
i
4. Return Result
- Return
dp[n]which indicates whether the entire stringscan be segmented
Key Insight
- The trie allows us to check all dictionary words starting at position
iin a single pass through the string, avoiding redundant prefix comparisons - Combined with DP, this achieves **O(n * L)** time complexity where
Lis the maximum word length in the dictionary - This is more efficient than checking each word individually, especially when the dictionary is large
Visualization
Input:
[l, e, e, t, c, o, d, e]
—
No animation available
Left (L)Right (R)ConvergedDone
0 steps