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.

Note: The shorter words used to form the concatenated word must exist in the original 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","catdog"]
Output: ["catdog"]
💡 Note: "catdog" can be formed from "cat" + "dog", which are both in the array
Example 3 — Edge Case with Single Word
$ Input: words = ["a"]
Output: []
💡 Note: No word can be formed from at least two other words since there's only one word

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
INPUTALGORITHMRESULTcatcatsdogcatsdogcatsdogcatsdogWords ArrayCheck each word forconcatenation possibility1Build word set for O(1) lookup2For each word, use DP to check3Try all possible split positions4Add valid concatenated wordsDP Check Example:catsdogcats --> cats|dog|catsAll parts exist in word set ✓["catsdogcats","dogcatsdog"]Concatenated WordsWords formed by joining2+ other words from arrayKey Insight:Use dynamic programming with word set lookup to efficiently check if each word can bedecomposed into valid dictionary words. Sort by length to process shorter words first.TutorialsPoint - Concatenated Words | Dynamic Programming
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
85.0K Views
Medium Frequency
~35 min Avg. Time
2.1K 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