Word Chaining
Find the circular chain in the given list of words.
We'll cover the following...
Statement
Given a list of words, figure out whether the given words can form a circular chain. Assume that a single word can never form a chain.
Two words can be chained together if the first word’s last letter is equal to the second word’s first letter.
Note: Assume that all the words are lower case.
Example
Consider the following words:
These words can form the following chain:
Sample input
Input will be a list of words:
list_words = ["eve", "eat", "ripe", "tear"]
Expected output
true
Try it yourself #
Solution
Naive solution
A naive solution for this problem is to find all the permutations of these strings recursively and return true once a chain is detected. The run time for this approach is O(n!).
Although, practically, it is faster as we prune permutations early if they do not conform to our chaining logic.
Optimized solution
A better solution is to do a linear pass of the word list and construct a graph that represents the start and end characters of each word. We need to add an edge from the starting character of a word to its ending character for each word in the list. If there exists a cycle in this graph containing all the nodes, then a chain can be formed.
To form a circular chain connecting all the words, the graph must be connected so that if we start traversing it from ...