Concatenated Words - Problem
Concatenated Words is a fascinating string manipulation problem that challenges you to identify words that can be formed by combining other words from the same collection.
Given an array of strings
Key Points:
• Words can be reused when forming concatenated words
• A concatenated word must use at least 2 other words
• The component words must exist in the original array
Example: If you have
Given an array of strings
words (without duplicates), return all the concatenated words in the given list. A concatenated word is defined as a string that is comprised entirely of at least two shorter words (not necessarily distinct) from the given array.Key Points:
• Words can be reused when forming concatenated words
• A concatenated word must use at least 2 other words
• The component words must exist in the original array
Example: If you have
["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamus", "rat", "ratcatdogcat"], then "catsdogcats" is concatenated because it can be formed from "cats" + "dog" + "cats". Input & Output
example_1.py — Basic concatenation
$
Input:
["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamus","rat","ratcatdogcat"]
›
Output:
["catsdogcats","dogcatsdog","ratcatdogcat"]
💡 Note:
"catsdogcats" can be formed by "cats"+"dog"+"cats", "dogcatsdog" can be formed by "dog"+"cats"+"dog", and "ratcatdogcat" can be formed by "rat"+"cat"+"dog"+"cat".
example_2.py — Single words
$
Input:
["cat","dog","catdog"]
›
Output:
["catdog"]
💡 Note:
Only "catdog" can be formed by concatenating "cat" and "dog". The individual words "cat" and "dog" are not concatenated words.
example_3.py — No concatenated words
$
Input:
["cat","dog","rat"]
›
Output:
[]
💡 Note:
None of these words can be formed by concatenating other words from the array, so the result is empty.
Visualization
Tap to expand
Understanding the Visualization
1
Organize Blocks
Sort building blocks by size, starting with the smallest ones
2
Build Foundation
Use small blocks as foundation pieces for larger constructions
3
Test Assembly
For each complex structure, use DP to see if it can be built from existing blocks
4
Identify Composites
Structures requiring 2+ blocks are composite (concatenated) words
Key Takeaway
🎯 Key Insight: By processing words in length order and using dynamic programming, we can efficiently identify which complex words are built from simpler components, ensuring optimal O(n log n + n × m²) performance.
Time & Space Complexity
Time Complexity
O(n log n + n × m²)
n log n for sorting, then n words each taking m² DP operations where m is average word length
⚡ Linearithmic
Space Complexity
O(n + m)
n for word set storage, m for DP array per word
⚡ Linearithmic Space
Constraints
- 1 ≤ words.length ≤ 104
- 1 ≤ words[i].length ≤ 30
- words[i] consists of only lowercase English letters
- All the strings of words are unique
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code