Concatenated Words

Given a list of words, return all words that can be formed by concatenating at least two shorter words from the same list. Pattern focus: Trie DFS Search. DFS with memoization lets you test whether a word can be composed from previously inserted dictionary pieces.

Input Format

words = array of lowercase words

Output Format

all concatenated words in lexicographic order

Constraints

  • 1 <= words.length <= 10^4
  • 1 <= total characters across all words <= 10^5
  • Words contain only lowercase English letters.

Examples

Example 1:

Input:

words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]

Output:

[catsdogcats,dogcatsdog,ratcatdogcat]

Explanation:

Each returned word can be built from at least two smaller dictionary words.

Example 2:

Input:

words = ["cat","dog"]

Output:

[]

Explanation:

No word can be formed by combining two or more shorter words.

Example 3:

Input:

words = ["a","aa","aaa","aaaa","aaaaa"]

Output:

[aa,aaa,aaaa,aaaaa]

Explanation:

Every word longer than one character can be decomposed into smaller dictionary pieces.

Loading...
Concatenated Words - Trie DSA Problem