Given a set of words, check if 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,

Consider the following set of words:
 
[ANT, OSTRICH, DEER, TURKEY, KANGAROO, TIGER, RABBIT, RAT, TOAD, YAK, HYENA]
 
 
The words can be rearranged as follows to form a circle. Note that, for any pair of consecutive words (X → Y) in the circle, the last character of the word X is the same as the first character of the word Y.
 
    ANT → TIGER → RABBIT → TOAD
     ↑                      ↓
   HYENA                   DEER
     ↑                      ↓
  OSTRICH                  RAT
     ↑                      ↓
  KANGAROO   ←  YAK   ←   TURKEY

Practice this problem

 
Prerequisite:

Eulerian cycle in directed graphs

 
The idea is to build a directed graph and for each word in the given set, add an edge from the first character to the last character in the graph. Now the problem is reduced to finding an Eulerian cycle in the constructed graph. If the graph has an eulerian circuit, then a circle can be formed; otherwise, not. A directed graph has an Eulerian cycle if and only if:

  1. Every vertex has in-degree == out-degree, and
  2. All of its non-isolated vertices belong to a single strongly connected component.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The given words can be rearranged

Java


Download  Run Code

Output:

The given words can be rearranged

Python


Download  Run Code

Output:

The given words can be rearranged

The time complexity of the above solution is the same as that of Kosaraju’s algorithm, i.e., O(V + E), where V and E are the total number of vertices and edges in the graph, respectively.