Concatenated Words
Master this topic with zero to advance depth.
Concatenated Words
Given an array of strings words (without duplicates), return all the concatenated words in the given list of words. A concatenated word is defined as a string that is entirely comprised of at least two shorter words in the given array.
Visual Representation
Words: ["cat", "dog", "catdog"]
DFS(0):
1. Prefixes found: "cat" (Trie matches).
2. Remaining: "dog".
3. DFS("dog"): Prefix found: "dog". Remaining: "".
4. SUCCESS -> "catdog" is concatenated.Examples
Level I: Set-based DFS
Intuition
Use a HashSet to store all words. For each word, check if it can be partitioned into at least two shorter words present in the Set using a recursive DFS with memoization. Simple but less space-efficient for prefix matching.
Level III: Trie + DFS + Memoization
Intuition
First, sort the words by length. This allows us to only search for a word's composition using words that were previously added to the Trie (which are guaranteed to be shorter). For each word, use DFS with a Trie to check if it can be broken into multiple pieces that are already in the Trie.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.