Skip to content

Instantly share code, notes, and snippets.

@spence
Created May 17, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spence/e6a0a5d38a44b3085f75 to your computer and use it in GitHub Desktop.
Save spence/e6a0a5d38a44b3085f75 to your computer and use it in GitHub Desktop.
Given a string of words, find all those that are anagrams.
def find_anagrams(words):
"""
Find anagrams in O(n*m) time and O(n) space.
Notes: returns all words in input that are anagrams of another word.
"""
anagrams = []
sorted_words = {}
for word in words: # O(n)
# Compute hash for string
sorted_word = ''.join(sorted(char for char in word)) # O(m)
if sorted_word not in sorted_words:
# No match, add word by its hash
sorted_words[sorted_word] = word
elif sorted_words[sorted_word] is not None:
# Value is not None, print matching words
anagrams.append(sorted_words[sorted_word])
anagrams.append(word)
# Mark as None so future words do not add previous match
sorted_words[sorted_word] = None
else:
# Value is None, add only the current word
anagrams.append(word)
return anagrams
print find_anagrams(['aba', 'baa', 'dsajk', 'aab', 'a', 'b', 'aslkdj', 'aba', 'jkdsa'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment