Concatenated Words

Hard · Tries · Array · String · Dynamic Programming · Depth-First Search · Trie

Problem

You are given an array of distinct strings words. A concatenated word is a string in words that can be written entirely as a concatenation of at least two shorter words from the same array. Pieces may repeat: a word can be used more than once.

Return all concatenated words in words, in any order.

Examples

Input: words = ["sun","flower","sunflower","sunsun","flow","er","sunflowers"]
Output: ["flower","sunflower","sunsun"]

"flower" = flow + er, "sunflower" = sun + flower, "sunsun" uses "sun" twice. Nothing supplies the trailing "s" of "sunflowers".

Input: words = ["a","b","ab","abc"]
Output: ["ab"]

"ab" = a + b, but "abc" would need a piece for "c".

Input: words = ["cat","dog"]
Output: []

A word made of one piece (itself) does not count.

Constraints

Approaches

Follow-up

With a trie of the known words, the DP can walk forward from each reachable position letter by letter and stop as soon as no word continues, which avoids hashing substrings that cannot match.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…