You are given a list of words. Decide whether all of them can be arranged into one circular chain.
Word x can be followed by word y when the last character of x equals the first character of y. The chain must use every word exactly once, and it must close: the last character of the final word must equal the first character of the first word. Return True if such a circular arrangement exists and False otherwise.
Function Signature
def can_chain_words(words: list[str]) -> bool:
Rules
-
Each entry of
words
is a separate word, so a string that appears twice in the list must be used twice.
-
A list with one word forms a circle when that word starts and ends with the same character.
Constraints
-
1 <= len(words) <= 10^5
-
1 <= len(words[i]) <= 100
-
words[i]
consists of lowercase English letters.
Examples
Input: words = ["abc", "cd", "da"]
Output: True
The order abc, cd, da works. "abc" ends with c and "cd" starts with c, "cd" ends with d and "da" starts with d, and "da" ends with a, which is where "abc" starts, so the chain closes.
Input: words = ["abc", "def", "ghi"]
Output: False
No word starts with c, so nothing can follow "abc" and the circle cannot be completed.
Input: words = ["ab", "ba", "cd", "dc"]
Output: False
"ab" and "ba" form a small circle, and so do "cd" and "dc", but no word links the letters a and b to the letters c and d. One circle through all four words is impossible.