Concatenated Words - Problem
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 comprised entirely of at least two shorter words (not necessarily distinct) in the given array.
Input & Output
Example 1 — Multiple Concatenated Words
$
Input:
words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
›
Output:
["catsdogcats","dogcatsdog","ratcatdogcat"]
💡 Note:
"catsdogcats" = "cats" + "dog" + "cats", "dogcatsdog" = "dog" + "cats" + "dog", "ratcatdogcat" = "rat" + "cat" + "dog" + "cat"
Example 2 — No Concatenated Words
$
Input:
words = ["cat","dog","bird"]
›
Output:
[]
💡 Note:
None of the words can be formed by concatenating other words in the array
Example 3 — Self-Concatenation
$
Input:
words = ["a","aa","aaa"]
›
Output:
["aa","aaa"]
💡 Note:
"aa" = "a" + "a", "aaa" = "a" + "aa" or "aa" + "a"
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
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of unique words to analyze
2
Process
Check each word to see if it can be split into existing words
3
Output
Return all words that are concatenations of at least 2 others
Key Takeaway
🎯 Key Insight: Sort by length and use DP to check if each word can be built from previously processed shorter words
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code