You are given a list of distinct words, words. A word is concatenated if it can be cut into two or more pieces, where every piece is a shorter word that is also in the list. The same word may be used as a piece more than once.
Return every concatenated word in the list, in any order.
Example 1
Input: words = ["sun", "flower", "sunflower", "flowers", "s", "sunflowers"] Output: ["sunflower", "flowers", "sunflowers"] Why: sun+flower, flower+s, sun+flower+s
2 more examples and the constraints
Example 2
Input: words = ["to", "do", "todo"] Output: ["todo"] Why: todo = to + do
Example 3
Input: words = ["ab", "abc"] Output: [] Why: "abc" would need "c", which is not in the list
Constraints
- 1 ≤ number of words ≤ 10,000
- 1 ≤ length of each word ≤ 30
- The words are distinct and hold only lowercase English letters
- All words together have at most 100,000 letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Word break with a setO(Σ L³)
- Trie walk from each splitO(Σ L²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Letter steps for 10,000 words of 10 letters | Verdict |
|---|---|---|---|
| Word break with a set | O(Σ L³) | Passes; slices and hashes every piece | |
| Trie walk from each split | O(Σ L²) | Best; no substrings copied |
L = length of a word; Σ sums over all words.
Edge cases to test
- The word itself. Every word is in the dictionary, so the whole word always matches. Skip the piece that runs from the start to the end.
- Longest match first fails. In
abcdwithab,abc,cd, takingabcleavesd. The table tries every split, soab+cdis found. - A piece used twice.
hahaisha+ha. Reuse is allowed. - Pieces that are concatenated too.
redoredocan useredo, which is itself concatenated. Any word in the list can be a piece. - Long dead ends.
aaa...abwith every run of a in the list has many partial splits, but the table visits each position once.
Common mistakes
- Letting a word count as a piece of itself, so every word is returned.
- Splitting greedily at the longest (or shortest) matching prefix instead of trying every split.
- Plain recursion without a memo or table, which takes exponential time on words like
aaaa...ab.
How to talk through it
- 1Clarify. Must there be at least two pieces? Can a piece repeat? Can the answer come back in any order?
- 2Reduce it. Each word is a word break question against the rest of the list.
- 3Set up the table.
ok[i]says the first i letters split. Fill it from left to right and skip the whole word as a single piece. - 4Improve the lookup. A trie lets each start position extend letter by letter, with no substring copies.
- 5Test out loud. Try
["to", "do", "todo"], a single word, and theab,abc,cd,abcdgreedy trap.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?