Concatenated Words (LeetCode 472): Solution and Explanation
Given a list of distinct words, return every word that can be built by gluing together two or more shorter words from the same list. The same shorter word may be used more than once.
Watch it run step by step
Try your own input and write the code →Intuition
For a single word this is the word break problem: can the string be split into pieces that are all dictionary words? The twist is that the dictionary is the list itself, and a word must not count as built from just itself. So for each word we ask whether it can be split into at least two pieces, all in the set.
The brute force tries every way to cut a word, which is 2^(L - 1) partitions for a word of length L. Most of that work repeats. Suppose "catsdogcats" fails when we split off "cat" first. Later splits often reach the same remaining suffix, such as "dogcats", and we would solve it again from scratch. Remembering the answer for each suffix string collapses the search to one evaluation per distinct suffix.
The reference solution expresses this with a recursive canForm(word). It tries every proper prefix. When the prefix is a known word, the rest succeeds if it is itself a word (that makes two pieces) or if it can be formed recursively from more pieces. Requiring the prefix to be strictly shorter than the word is what enforces the at least two words rule, since the top-level call never lets a word match itself as one whole piece. The memo dictionary is shared across all words, so suffixes computed while checking one word are reused for the next.
Approach: Hash set with memoized word break
- Put every word in
wordSetfor O(1) membership tests and create an emptymemo. - Define
canForm(word): return the cached answer ifwordis inmemo. - For each split point
ifrom 1 tolen(word) - 1, takeprefix = word[:i]andsuffix = word[i:]. - If
prefixis inwordSetand eithersuffixis inwordSetorcanForm(suffix)is true, cache true and return true. - If no split works, cache false and return false.
- Loop over all words, skip empty strings and collect each word for which
canFormreturns true.
Step-by-step example
words = ["cat", "cats", "dog", "catsdog"]
- "cat": no proper prefix ("c", "ca") is in the set, so it is not concatenated.
- "cats": the prefix "cat" is a word, but the suffix "s" is not a word and
canForm("s")is false. Result false. - "dog": no prefix matches. Result false.
- "catsdog": at i = 3, prefix "cat" matches, but
canForm("sdog")fails because none of "s", "sd" or "sdo" are words. - At i = 4, prefix "cats" matches and suffix "dog" is in the set, so "catsdog" is concatenated.
- The result is ["catsdog"].
Code: Python, Java, C++
1class Solution:
2 def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
3 wordSet = set(words)
4 memo = {}
5
6 def canForm(word):
7 if word in memo:
8 return memo[word]
9
10 for i in range(1, len(word)):
11 prefix = word[:i]
12 suffix = word[i:]
13
14 if prefix in wordSet:
15 if suffix in wordSet or canForm(suffix):
16 memo[word] = True
17 return True
18
19 memo[word] = False
20 return False
21
22 result = []
23 for word in words:
24 if word and canForm(word):
25 result.append(word)
26
27 return result1class Solution {
2 Set<String> wordSet;
3 Map<String, Boolean> memo = new HashMap<>();
4
5 public List<String> findAllConcatenatedWordsInADict(String[] words) {
6 wordSet = new HashSet<>(Arrays.asList(words));
7 List<String> result = new ArrayList<>();
8
9 for (String word : words) {
10 if (word.length() > 0 && canForm(word)) {
11 result.add(word);
12 }
13 }
14
15 return result;
16 }
17
18 private boolean canForm(String word) {
19 if (memo.containsKey(word)) return memo.get(word);
20
21 for (int i = 1; i < word.length(); i++) {
22 String prefix = word.substring(0, i);
23 String suffix = word.substring(i);
24
25 if (wordSet.contains(prefix)) {
26 if (wordSet.contains(suffix) || canForm(suffix)) {
27 memo.put(word, true);
28 return true;
29 }
30 }
31 }
32
33 memo.put(word, false);
34 return false;
35 }
36}1class Solution {
2public:
3 unordered_set<string> wordSet;
4 unordered_map<string, bool> memo;
5
6 vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
7 wordSet = unordered_set<string>(words.begin(), words.end());
8 vector<string> result;
9
10 for (const string& word : words) {
11 if (!word.empty() && canForm(word)) {
12 result.push_back(word);
13 }
14 }
15
16 return result;
17 }
18
19 bool canForm(const string& word) {
20 if (memo.count(word)) return memo[word];
21
22 for (int i = 1; i < word.size(); i++) {
23 string prefix = word.substr(0, i);
24 string suffix = word.substr(i);
25
26 if (wordSet.count(prefix)) {
27 if (wordSet.count(suffix) || canForm(suffix)) {
28 return memo[word] = true;
29 }
30 }
31 }
32
33 return memo[word] = false;
34 }
35};Time and space complexity
O(n × L³)
For each of n words of length up to L, memoization limits the work to O(L) distinct suffixes, each trying O(L) splits, and every split slices and hashes a string of length O(L).
O(n × L²)
The memo can store up to L suffix strings per word, each of length up to L, plus the word set itself.
Other approaches
Sort by length and run word break DP (time O(n log n + n × L³), space O(n × L))
Sort words by length and process them shortest first. For each word, run the standard boolean DP dp[i] over its prefixes against a set that contains only the shorter words seen so far, then add the word to the set. Because a word is never in its own dictionary, any successful break automatically has at least two pieces.
Trie with DFS (time O(n × L²), space O(n × L))
Insert all words into a trie and, for each word, walk the trie from every split position, recursing whenever a word ends. Walking the trie avoids building substrings, which helps when words share long prefixes.
Common mistakes
- Letting the split point reach
len(word), which treats the whole word as one piece and marks every word as concatenated. - Starting the split loop at 0. If the empty string is in the list, the empty prefix matches and every word counts as "" plus itself.
- Skipping memoization, which makes inputs like many words of repeated "a" characters exponential.
- Caching results under the original word only and recomputing suffixes, which loses most of the benefit.
Frequently asked questions
How is Concatenated Words related to Word Break?
It is Word Break run once per word, with the rest of the list as the dictionary and an extra rule that at least two pieces are used. The memoized split check is the same idea.
How do you make sure a word is not counted as made of itself?
Only proper prefixes are tried, so the first piece is always shorter than the word. The remaining suffix may be a single word, which gives exactly two pieces.
Trie or hash set for Concatenated Words?
A hash set with memoization is shorter and usually fast enough. A trie avoids repeated substring hashing and can be quicker on long words with shared prefixes, at the cost of more code.