Skip to content

Instantly share code, notes, and snippets.

@sahands
Last active December 19, 2015 19:18
Show Gist options
  • Save sahands/6004753 to your computer and use it in GitHub Desktop.
Save sahands/6004753 to your computer and use it in GitHub Desktop.
Interview Question: Grouping Word Anagrams (Facebook)
import collections
def sort_hash(word):
return ''.join(sorted(word))
def count_letters_hash(word):
d = collections.defaultdict(int)
for c in word:
d[c] += 1
return tuple(d.items())
def group_anagrams(words, pre_hash_function):
result = {}
for w in words:
s = pre_hash_function(w.lower())
if s in result:
result[s] |= {w}
else:
result[s] = {w}
return result.values()
#usage:
>>> group_anagrams(['tsar', 'rat', 'tar', 'star', 'tars', 'cheese'], sort_hash)
[set(['tars', 'tsar', 'star']), set(['cheese']), set(['rat', 'tar'])]
>>> group_anagrams(['tsar', 'rat', 'tar', 'star', 'tars', 'cheese'], count_letters_hash)
[set(['tars', 'tsar', 'star']), set(['cheese']), set(['rat', 'tar'])]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment