5 ms·
you only need to go through the array one time - here you are doing it multiple times.... also, you can define a order independent hashing function, that just
by nartz 11y ago
you only need to go through the array one time - here you are doing it multiple times....
also, you can define a order independent hashing function, that just maybe assigns prime numbers to each letter and adds them up....
instead...
hashed_words = {}
anagrams = []
for word in words:
h = compute_hash(word)
w = hashed_words.get(h)
if w == True
// we've already encountered another anagram, just add it
anagrams.append(word)
elsif w
//case where both w and word are anagrams, so append both to list
// and set the value to True, so we can shortcircuit this operation in the future
anagrams.append(w); anagrams.append(word);
hashed_words[h] = True //flag indicating weve seen this word before
else
// first time we are seeing this, so lets just set it
hashed_words[h] = word
return anagrams