Concatenated Words solution explained
Concatenated Words asks you to return every word in a list that can be written as two or more shorter words from the same list joined end to end. Sort the words by length and run a word-break DP on each one against the set of words already seen, which by construction are no longer than it; add the word to the set after checking it. Alternatively, put every word in a trie and search each word with memoization. Both run in roughly O(Σ L²) dictionary steps, where L is a word's length.
By Evin JohnPublished 8 min read
The problem, in plain terms
You get a list of different words. Some of them can be built by gluing together other words from the same list, using any word as many times as you like, as long as the result uses at least two pieces. Return all such words, in any order.
words: sun, flower, sunflower, flowerpot, pot, sunflowerpot, suns, potsun, unpot
sunflower = sun + flower
flowerpot = flower + pot
sunflowerpot = sun + flower + pot (or sunflower + pot)
potsun = pot + sun
suns no: there is no "s"
unpot no: there is no "un"
answer: sunflower, flowerpot, sunflowerpot, potsunQuestions to ask: can the list contain an empty string (it should be ignored, or every word becomes a trivial split), can the same word appear twice, and does the output order matter. Also confirm that one piece is not enough, which is what stops every word from matching itself.
Why interviewers like it
It tests whether you recognize a known problem inside a new one. Once you say this is word break for every word, the remaining questions are about efficiency: how to avoid matching a word with itself, how to keep the dictionary small, and how to stop the split search from repeating work. A trie version also opens a conversation about prefix structures, so it often appears in trie or string rounds.
Brute force
For each word, try every first piece that is a dictionary word, then recurse on the rest, counting pieces, and accept the word when the remainder is used up with at least two pieces. Without memory this explodes on repetitive input. With the words a, aa, up to twenty a's, plus the same twenty a's followed by b, the plain recursion made 1,048,576 calls to reject that last word, because every way of cutting the a's is tried before the b ends each attempt.
The optimal approach: sort by length, then word break
Pattern: word break dynamic programming, applied per word. A word can only be made of strictly shorter words, so sort by length and walk through the list, keeping a set of the words already handled. For each word, run the classic prefix DP: ok[i] is true when the first i letters can be cut into words from the set. Since the word itself is not in the set yet, any successful split must use at least two pieces, which is exactly the rule. Then add the word to the set. Because the set never holds anything longer than the current word, you can also stop the inner loop from looking further back than that length.
def concatenated_words(words):
known = set() # words already checked; none is longer than the current one
longest = 0 # length of the longest word in known
found = []
for word in sorted(set(words), key=len):
if word and can_split(word, known, longest):
found.append(word)
if word:
known.add(word)
longest = len(word)
return found
def can_split(word, known, longest):
# ok[i] is True when word[:i] can be cut into words from known
ok = [True] + [False] * len(word)
for end in range(1, len(word) + 1):
for start in range(max(0, end - longest), end):
if ok[start] and word[start:end] in known:
ok[end] = True
break
return ok[len(word)]Two details are worth saying out loud. set(words) removes duplicates, so a word that appears twice cannot be split into one copy of itself. And empty strings are skipped twice: they are never checked and never added to the set, since an empty piece would let any split go on forever without consuming letters.
Trie and memoized search in JavaScript
The second approach puts every word into a trie and, for each word, walks the trie from a start position. Each time the walk reaches the end of a dictionary word, it tries to cut there and continue from the next letter. A memo per word records which start positions can finish the word, so each position is solved once. The piece count matters only at the top level: the whole word reaching the end of itself in the trie counts as one piece and must not be accepted alone.
function concatenatedWords(words) {
const root = { next: {}, end: false };
for (const w of words) {
let node = root;
for (const ch of w) node = node.next[ch] ??= { next: {}, end: false };
if (w.length > 0) node.end = true;
}
// Can word[start..] be cut into dictionary words? count = pieces so far.
function cut(word, start, count, memo) {
if (start === word.length) return count >= 2;
if (count > 0 && memo[start] !== undefined) return memo[start];
let node = root, found = false;
for (let i = start; i < word.length && !found; i++) {
node = node.next[word[i]];
if (!node) break;
if (node.end) found = cut(word, i + 1, count + 1, memo);
}
if (count > 0) memo[start] = found;
return found;
}
return words.filter((w) => w.length > 0 && cut(w, 0, 0, []));
}The memo is only used once at least one piece has been cut, because only then does the answer for a start position stop depending on how many pieces came before. The trie avoids hashing substrings: walking from a start position reads each letter once and finds every dictionary prefix along the way. This version keeps the input order in its output; the Python one returns words in length order.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Unmemoized split search | Exponential in L on repetitive input | O(L) stack |
| Sort + word break with a hash set | O(W log W + Σ L × min(L, M) × L), the last L for slicing and hashing | O(total letters) |
| Trie + memoized walk | O(Σ L²) | O(total letters) for the trie |
In practice both are fast because most cuts fail early. The trie version has the cleaner bound since it never builds substrings; the sorted version is shorter to write and easier to explain first.
Edge cases to test
- A list with only one word, or with no word made of others: the answer is empty.
- An empty string in the list, which must not count as a piece.
- A word made of one other word repeated, like ab and abab.
- A word that has a split only through a longer piece first, like sunflowerpot, which works as sun + flower + pot and as sunflower + pot.
- Long runs of one letter, which punish any version without memoization.
Common mistakes
- Checking each word against the full set, which includes the word itself, so every word passes.
- Accepting a split of exactly one piece.
- Letting the empty string into the dictionary.
- Running word break without memoization or a DP table, which times out on repetitive inputs.
- Recomputing the longest word length inside the loop over words, which quietly adds a factor of W.
How to explain it out loud
Fictional example
- Candidate
- For one word, this is word break: can I cut it into dictionary words. The twist is that the dictionary is the rest of the list, and I need at least two pieces.
- Candidate
- If I sort by length and add each word to the set only after checking it, the set never contains the word itself, so any split I find has two or more pieces automatically.
- Candidate
- The check is a prefix DP over the word, so about length squared lookups per word. If substring hashing worries you, I can switch to a trie and walk it from each cut point with a memo.
Related problems
The prefix tree used in the JavaScript version is built step by step in Implement Trie. Using a trie to find the shortest dictionary prefix of each word is Replace Words, and matching dictionary words against the end of a growing text is Stream of Characters. For another question about cutting strings into pieces, with swaps allowed, see Scramble String.
Rehearsing with Natively
Questions like this reward saying the known pattern early, so rehearse that sentence. While you practice on Mac or Windows, Natively can read the prompt from a screenshot and write an approach and code to compare with yours, including the sort-by-length trick if you missed it. The saved transcript lets you check how long it took you to name word break. Read about AI help for LeetCode-style practice.
Questions people ask
How do you solve Concatenated Words?
Sort the words by length. For each word, run a word break DP against the set of words already processed, then add the word to the set. Because the word is not yet in the set, any split found has at least two pieces.
Why sort by length in Concatenated Words?
A word can only be built from strictly shorter words, so after sorting, the set of earlier words is all you need as a dictionary, and the word can never match itself.
What is the time complexity of Concatenated Words?
About O(L²) dictionary steps per word of length L, so O(Σ L²) with a trie, plus slicing and hashing costs in the hash-set version and O(W log W) for sorting.
Can a trie solve Concatenated Words?
Yes. Insert every word, then for each word walk the trie from each cut point, recursing whenever a dictionary word ends. Memoize by start position and require at least two pieces.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
