Word Break II
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trie.
Word Break II
Given a string
s and a string dictionary wordDict, return all possible sentences that can be formed by adding spaces to s such that each word is a valid dictionary word.Visual Representation
s = "catsanddog", dict = ["cat","cats","and","sand","dog"]
Trie path 1: root -> c -> a -> t -> s (word) -> a -> n -> d (word) -> d -> o -> g (word)
Trie path 2: root -> c -> a -> t (word) -> s -> a -> n -> d (word) -> d -> o -> g (word)
Sentences:
1. "cats and dog"
2. "cat sand dog"Examples
Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
Output: ["cats and dog","cat sand dog"]
Approach 1
Level I: Standard Recursion
Intuition
Iterate through the string s. If a prefix exists in the dictionary, recursively solve for the remaining suffix. O(2^N).
⏱ O(2^N)💾 O(N)
Approach 2
Level III: Trie + DFS + Memoization
Intuition
Use a Trie to store words for fast prefix lookups. Combine DFS with memoization to store results for each starting index.
⏱ O(N * 2^N)💾 O(N * 2^N)
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.