I am trying to solve this problem in CodeEval.
In this challenge we suggest you to play in the known game "Word chain" in which players come up with words that begin with the letter that the previous word ended with. The challenge is to determine the maximum length of a chain that can be created from a list of words.
Example:
Input:
soup,sugar,peas,rice
Ouput:
4
Explanation: We can form a chain of 4 words like this: "soup->peas->sugar->rice".
Constraints:
- The length of a list of words is in range [4, 35].
- A word in a list of words is represented by a random lowercase ascii string with the length of [3, 7] letters.
- There is no repeating words in a list of words.
My attempt: My approach is to model the words as a graph, such that each word in the inputs represents a node and there is an (directed) edge between from wordi to wordj if last character of wordi is equal to the first character of wordj.
After that I am running bfs from each node and computing the length of the farthest node from the this node. The final result is the maximum value possible for all nodes.
But this approach is not giving me a full score. Hence, my question is how to solve this problem correctly and efficiently?