AlgoInsight

DSA problem

Concatenated Words

HardTriesPattern: Triestop600AmazonMicrosoftGoogleMetaBloomberg

Given an array of strings words (without duplicates), return all the concatenated words in the given list. A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.

For example, if the input contains "cat", "dog", and "catdog", then "catdog" is a concatenated word because it splits into "cat" + "dog". A word formed by a single shorter word does not count — there must be at least two parts. A word does not count as a part of itself.

The brute-force approach is to test every word against every pair of substrings, which is prohibitively slow. A faster idea sorts words by length and uses DP per word: for each suffix position, check if the prefix ending there is a previously inserted word. Combined with a Trie this gives a very efficient solution.

The optimal strategy uses a Trie augmented with a memoized DFS. Sort words by length ascending so any potential building block of a word is processed before the word itself. For each word w, walk the Trie character by character — whenever we encounter a Trie node marked as a word ending, we have one valid split, and we recurse on the remaining suffix to ask "can the rest also be expressed as ≥ 1 concatenation?". A memo keyed by suffix index prevents exponential blow-up. Finally, insert w itself into the Trie so longer words can use it as a building block.

Examples

Example 1
Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
Explanation: "catsdogcats" = "cats" + "dog" + "cats"; "dogcatsdog" = "dog" + "cats" + "dog"; "ratcatdogcat" = "rat" + "cat" + "dog" + "cat". The remaining words cannot be split into two or more dictionary words.
Example 2
Input: words = ["cat","dog","catdog"]
Output: ["catdog"]
Explanation: "catdog" splits into "cat" + "dog", both of which are in the input list. "cat" and "dog" alone are single words and therefore not concatenated.
Example 3
Input: words = ["a","b","ab","abc"]
Output: ["ab"]
Explanation: "ab" splits into "a" + "b". "abc" cannot be split into two or more input words ("ab" + "c" fails because "c" is missing).

Constraints

4 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

triedfsdynamic-programmingstringmemoization

Browse all DSA problems