You are given an array of strings, return true if and only if all the strings can be connected in one chain.
Condition for connectivity is, if the last character of one string matches the first character of the second string, then the two strings can be connected.
Example : String []arr ={"abc", "cde", "cad" , "def" , "eac"}
will return true because all strings can be connected in one chain.
"abc"->"cde"->"eac"->"cad"->"def"
Another Example: String []arr ={"acb" , "cde", "def", "ead" }
returns False because
"cde"->"ead"->"def"
is the possible chain but “acb” is left out.
Note: It's not necessary to start with the first string and form the chain, It may happen that you won’t get a chain if you start with the first string. You can get a chain if you start with any other string. If there exists a possible chain, then your solution should return true.
In the second example, if the first String was suppose to be “fcb”
, then a possible chain would have existed, "cde"->"ead"->"def"->"fcb"
so True.
POSSIBLE SOLUTION (what i am thinking): Consider each string as a graph Node and connect the nodes if condition is satisfied. Once done, problem reduces to finding,
if there exists a Hamiltonian Cycle in a graph
, which is NP-Complete problem.
Anyone suggest some algorithm or any other solutions?