Given an array of lowercase strings A[] of size N, determine if the strings can be chained together to form a circle. A string X can be chained together with another string Y if the last character of X is same as first character of Y. If every string of the array can be chained, it will form a circle.
For eg for the array arr[] = {"for", "geek", "rig", "kaf"} the answer will be Yes as the given strings can be chained as "for", "rig", "geek" and "kaf"
Example 1:
Input:
N = 3
A[] = { "abc", "bcd", "cdf" }
Output:
0
Explaination:
These strings can't form a circle
because no string has 'd'at the starting index.
Example 2:
Input:
N = 4
A[] = { "ab" , "bc", "cd", "da" }
Output:
1
Explaination:
These strings can form a circle
of strings.
My working correct code:
class Solution:
def isCircle(self, N, A):
visited = set()
item1 = A[0]
curr = item1[-1]
visited.add(item1)
for _ in range(len(A)):
for item in A:
if item not in visited and item[0] == curr:
visited.add(item)
curr = item[-1]
# return visited
if len(visited) == len(A):
return 1
else:
return 0
Current Time Complexity:
O(n2)
Expected Time Complexity:
O(n)
How to make this more efficient and do the same work in a lot lesser time?