Created
May 17, 2015 14:17
-
-
Save spence/e6a0a5d38a44b3085f75 to your computer and use it in GitHub Desktop.
Given a string of words, find all those that are anagrams.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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