Identify Compound Words in a Dictionary
Dynamic ProgrammingModel answerLast updated
Find all strings in a list that can be constructed by concatenating two or more smaller strings from the same list.
Given an array words of non-empty, lowercase English strings, identify every string that can be fully constructed by joining together two or more strings from the same array.
Individual component strings can be reused multiple times.
Write a function that returns a list of all such compound strings.
Constraints
- $1 \le \text{words.length} \le 10^5$
- The total sum of string lengths across the array does not exceed $1,000,000$.
- All strings consist only of lowercase English letters.
- The returned list can contain the matching words in any order.
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"
Example 2
Input: words = ["a", "b", "ab", "abc"]
Output: ["ab"]
Explanation: "ab" can be formed by "a" + "b".
Hints
Hint 1
If you sort the words by length in ascending order, any word that can form a longer word must appear before it.
Hint 2
This problem is a variation of the Word Break problem. You can evaluate whether a string is valid using Dynamic Programming.
Hint 3
To prevent a word from satisfying the criteria by matching itself, only include words of strictly shorter length in your lookup set during evaluation.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach 1: Length-Sorted Set + Dynamic Programming
Strategy
The problem asks us to determine if a target word can be split into a sequence of smaller words present in the dictionary. This is a variation of the classic Word Break problem.
A key property is that any component word forming a target word must be strictly shorter than the target word itself (since all words are non-empty and at least two words are required).
- Sort by Length: Sort the unique input words in ascending order of length.
- Incremental Dictionary: Maintain a hash set of valid constituent words processed so far. When evaluating the current word
w, the hash set only contains words that are strictly shorter thanw(or equal length but processed earlier, though equal-length matches can be ignored if we deduplicate). This cleanly avoids the edge case where a word matches itself as a single piece. - Dynamic Programming (Word Break):
- For a word
wof length $L$, definedp[i]as a boolean indicating whether prefixw[:i]can be decomposed into existing dictionary words. - Base case:
dp[0] = True. - Transition:
dp[i] = Trueif there exists some index $j < i$ such thatdp[j] == Trueandw[j:i]is in our hash set.
- For a word
- Optimization (Length Constraints): Instead of checking every index $j \in [0, i-1]$, maintain a list of all word lengths currently present in our hash set. We only check
j = i - lengthfor valid word lengths.
Complexity Analysis
- Time Complexity:
- Sorting takes $O(N \log N + \sum |w_i|)$, where $N$ is the number of words.
- For each word of length $L$, the DP state takes $O(L \cdot D)$ slice checks, where $D$ is the number of distinct lengths present in the dictionary so far. Because the sum of all lengths is $\le 1,000,000$, the number of distinct word lengths $D$ is at most $\approx \sqrt{2 \cdot 10^6} \approx 1414$.
- In practice, slice-and-hash lookups are very fast, making the overall runtime well within limits.
- Space Complexity: $O(\sum |w_i|)$ to store the set of words and $O(\max(L))$ auxiliary space for the
dparray.
Python Code
def find_all_concatenated_words(words: list[str]) -> list[str]:
# Deduplicate and sort words by length
unique_words = sorted(set(words), key=len)
seen_words = set()
distinct_lengths = []
result = []
def can_form(word: str) -> bool:
if not seen_words:
return False
n = len(word)
dp = [False] * (n + 1)
dp[0] = True
for i in range(1, n + 1):
for length in distinct_lengths:
if length > i:
break
# If prefix up to i - length is valid and substring matches a word
if dp[i - length] and word[i - length:i] in seen_words:
dp[i] = True
break # Found a valid split for index i, move to next i
return dp[n]
for word in unique_words:
if not word:
continue
if can_form(word):
result.append(word)
seen_words.add(word)
if not distinct_lengths or distinct_lengths[-1] != len(word):
distinct_lengths.append(len(word))
return result
Approach 2: Trie + Iterative Dynamic Programming / Memoized Search
Strategy
Instead of extracting substrings and computing hash values, we can store existing dictionary words in a Trie.
- Process words in increasing order of length (same length-sorting idea).
- For each word, use the Trie to check if it can be partitioned into valid components.
- From a valid starting position
sin the word (wherereach[s] == True), walk down the Trie character by character (word[k]). - Whenever we hit a terminal node in the Trie at character index
k, it meansword[s:k+1]is a valid dictionary word. We markreach[k+1] = True.
This avoids substring slicing and hashing entirely.
Complexity Analysis
- Time Complexity: $O(\sum L^2)$ worst-case time for Trie traversal across all words, but prunes extremely fast in practice when prefix matches fail early.
- Space Complexity: $O(\text{Total Characters} \cdot \Sigma)$ for storing the Trie, where $\Sigma = 26$ is the alphabet size.
Python Code
def find_all_concatenated_words_trie(words: list[str]) -> list[str]:
unique_words = sorted(set(words), key=len)
trie = {}
END_MARKER = "$"
result = []
def can_form(word: str) -> bool:
n = len(word)
if n == 0 or not trie:
return False
# reach[i] tracks whether word[:i] can be formed by existing trie words
reach = [False] * (n + 1)
reach[0] = True
for start in range(n):
if not reach[start]:
continue
curr = trie
for end in range(start, n):
char = word[end]
if char not in curr:
break
curr = curr[char]
if END_MARKER in curr:
reach[end + 1] = True
if reach[n]:
return True
return reach[n]
def insert(word: str):
curr = trie
for char in word:
curr = curr.setdefault(char, {})
curr[END_MARKER] = True
for word in unique_words:
if not word:
continue
if can_form(word):
result.append(word)
insert(word)
return result
Common Corner Cases & Interview Pitfalls
- Self-Matching: A word like
"cat"should not be identified as compound just because"cat"is in the word list. Sorting by length and adding words to the dictionary after checking ensures a word is never matched against itself. - Duplicate Input Words: If
"cat"appears twice inwords, the second occurrence must not use the first occurrence to count as a compound word (unless formed by smaller parts like"c" + "at"). Deduplicating input list initially viaset(words)eliminates this risk. - Single-Character Words: Words of length 1 (e.g.,
"a") cannot be compound words because components must have length $\ge 1$ and at least 2 components are needed. However, length-1 words are essential potential components for longer words. - Recursion Limit: Recursive DFS solutions without explicit depth limits can trigger
RecursionErrorin Python on long strings. The iterative DP methods demonstrated above avoid stack overflows.