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
Concatenated Words Problem OverviewInput: ["cat","cats","catsdogcats","dog","dogcatsdog","rat","ratcatdogcat"]Check each word for concatenation possibilitycatsdogcatsdogcatsdogratcatdogcatcats+dog+catsdog+cats+dograt+cat+dog+catOutput: ["catsdogcats","dogcatsdog","ratcatdogcat"]
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
Asked in
Amazon 35 Google 28 Microsoft 22 Facebook 18
125.0K Views
Medium Frequency
~35 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen