Both solutions grow linearly as the number of words in the dictionary grows (we make a single pass through the dictionary and compare if it is an anagram).
Calling anagram_Onlogn multiplies O(n*log(n)) to the runtime, where n is the length of words. This is because it uses sorting to compare words ==> O(dictionary_size * word_size * log(word_size))
Calling anagram_On multiples O(word_size) to the runtime since we use hashmaps (python dicts) to compare words linearly on their size ==> O(dictionary_size * word_size)
defgrabscrab(jumble,dictionary):words=[]forwordindictionary:ifanagram_On(jumble,word):words.append(word)returnwords# n*log(n) comparison - better than n^2 but worse than n
defanagram_Onlogn(worda,wordb):alist=list(worda)blist=list(wordb)alist.sort()blist.sort()return(alist==blist)# optimal comparison - we can't do better than linear since we have to at least read each letter
defanagram_On(worda,wordb):adict=make_dict(worda)bdict=make_dict(wordb)returnadict==bdictdefmake_dict(word):d={}forletterinword:ifletternotind:d[letter]=0d[letter]+=1returndprint(grabscrab("ortsp",["sport","parrot","ports","matey"]))print(grabscrab("trisf",["first"]))print(grabscrab("oob",["bob","baobab"]))print(grabscrab("ainstuomn",["mountains","hills","mesa"]))print(grabscrab("oolp",["donkey","pool","horse","loop"]))
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Python, two solutions:
Both solutions grow linearly as the number of words in the dictionary grows (we make a single pass through the dictionary and compare if it is an anagram).
Calling anagram_Onlogn multiplies O(n*log(n)) to the runtime, where n is the length of words. This is because it uses sorting to compare words ==> O(dictionary_size * word_size * log(word_size))
Calling anagram_On multiples O(word_size) to the runtime since we use hashmaps (python dicts) to compare words linearly on their size ==> O(dictionary_size * word_size)