Concatenated Words
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trie.
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
Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
Approach 1
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.
⏱ O(N * L^2)💾 O(N * L)
Approach 2
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.
⏱ O(N * L^2) where L is max length.💾 O(N * L) for Trie.
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.