Given a list of distinct lowercase words, return every word in the list that can be formed by joining two or more words from the same list end to end.
Function Signature
def find_compound_words(words: list[str]) -> list[str]:
Rules
-
A word
w
in the list is compound when
w
equals the concatenation
p1 + p2 + ... + pm
for some
m >= 2
, where every piece
pi
is a word in the list.
-
The same word may be used as a piece more than once. Because there are at least two nonempty pieces, every piece is shorter than
w
, so a word never counts as a piece of itself.
-
Return the compound words in the order in which they appear in
words
. Return an empty list if there are none.
Constraints
-
1 <= len(words) <= 10^4
-
1 <= len(words[i]) <= 30
-
The total length of all the words is at most
10^5
.
-
Every word consists of lowercase English letters, and all words are distinct.
Examples
Example 1
Input: words = ["sun", "flower", "sunflower", "flowers", "s", "sunflowers", "pot"]
Output: ["sunflower", "flowers", "sunflowers"]
"sunflower" is "sun" + "flower", "flowers" is "flower" + "s", and "sunflowers" is "sun" + "flower" + "s" (or "sun" + "flowers"). None of the other words can be split into words from the list.
Example 2
Input: words = ["ab", "abab", "aba", "b"]
Output: ["abab"]
"abab" is "ab" + "ab", using the same word twice. "aba" would need the remaining piece "a", which is not in the list, and "ab" would need "a" + "b".
Example 3
Input: words = ["x", "y"]
Output: []