In this tutorial, we will learn whether the strings can be chained to form a circle. To make any string into a circle then the last element of a string has to be the same as the first element of the next string. If this is satisfied then the circle is formed with the strings.
Find the strings that can be chained to form a circle
For a better understanding of this concept, we use the set of stings are:
input_array = ["abc", "cde", "efg", "gah"]
In this, we can see that the input_array of the last element of the string and the first element of the next string are the same in that case we can say that it will form a circle.
For more clarity, we will go through the code
class CircleChecker: def isCircle(self, arr): visited = set() first_item = arr[0] curr = first_item[-1] visited.add(first_item) for _ in range(len(arr)): for item in arr: if item not in visited and item[0] == curr: visited.add(item) curr = item[-1] if len(visited) == len(arr): return ("Yes, it forms a circle") else: return ("No, it doesn't form a circle") input_array = ["abc", "cde", "efg", "gah"] checker = CircleChecker() print(checker.isCircle(input_array))
Output:
Yes, it forms a circle