The code below is for a challenge that I did recently. I estimate the runtime of this function to be O(n^2)
but I am a bit unsure if that is indeed correct, as the if statement line is somewhat expensive and I don't know to what extent should I factor that into my calculation.
Explanation of the If condition from the main code.
Counter
-> Dict constructing method of runtime O(n) and operations are O(1)
j not in tupleVal
-> O(n) runtime
Main Code
from collections import Counter
def funWith(texts):
words = set()
tuples = (0,)
for i in range(0,len(text)):
for j in range(i+1,len(text)):
if Counter(text[i]) == Counter(text[j]) and j not in tuples :
tuples +=(j,)
words.add(text[i])
return (sorted(list(words)) if len(words) > 0 else text)
text = ["cncvbn", "fdhfh", "anagrartyrtyms","cnvcbn"]
print(funWithAnagrams(text))
Any helps appreciated.
Thanks