You are given an array/list of words, your task is to check whether the individual words can be rearranged to form a circle.
Two words, ‘X’ and ‘Y’, can be put together in a circle if the last character of ‘X’ is the same as the first character of ‘Y’ or vice versa.
For Example:For the array [ “TUNA”, “TIGER”, “RABBIT”, “RAT”, “ANTEATER” ],
A possible circle can be:

The first line contains a single integer ‘T’ denoting the number of test cases to be run. Then the test cases follow.
The first line of each test case contains a single integer ‘N’, representing the size of the array.
The second line of each test case contains ‘N’ space-separated strings representing the words of the given array.
Output Format:
For each test case print ‘true’ if you can make a circle by rearranging the given words, else print ‘false’.
Output for each test case will be printed in a separate line.
Note
You are not required to print anything, it has already been taken care of. Just implement the function.
1 <= T <= 100
1 <= N <= 10^5
1 <= L <= 20
Where L is the length of each word in the given array.
It is guaranteed that the sum of N over all test cases doesn’t exceed 10^5.
Time Limit: 1 sec.
2
6
DONE LAST EQUAL TOSS SOME END
5
ROPE NONE RUN EAR EXPERIENCE
true
false
For the first test case, the words can be rearranged as:
For the second test case, no possible way exists.
2
4
NOW AGAIN WONDER GO
3
CHECK SYNC KEYS
false
true
Try to convert the given problem into a directed graph problem.
We will build a directed graph and for each word, we will add an edge from the first character to the last character in the graph. Now we just have to check whether the graph contains an Eulerian cycle or not. If it contains an Eulerian cycle, then we can form a circle.
The conditions for the existence of an Eulerian cycle in a directed graph are:
Eulerian Cycle: An Eulerian Cycle is a trail that starts and ends at the same graph vertex. In other words, it is a graph cycle that uses each graph edge exactly once.
You can learn more about Eulerian Cycle at the given link:
https://mathworld.wolfram.com/EulerianCycle.html
Algorithm:
O(N), where ‘N’ is the size of the array.
The time complexity will be similar to that of ‘dfs’ i.e O( V + E), where ‘V’ is the number of vertices and ‘E’ is the number of edges. In this problem, the maximum number of vertices can be 26, and the number of edges will be N. So the overall time complexity will be O(N).
O(N), where ‘N’ is the size of the array.
We are taking three vectors, ‘vis’, ‘in’, ‘out’, of size ‘N’, and two graphs of size ‘N’.
So the overall space complexity will be O(N).