Skip to content

Instantly share code, notes, and snippets.

@les-peters
Last active November 22, 2021 21:11
Show Gist options
  • Select an option

  • Save les-peters/3c6610495413fc6bb78da67b4a215121 to your computer and use it in GitHub Desktop.

Select an option

Save les-peters/3c6610495413fc6bb78da67b4a215121 to your computer and use it in GitHub Desktop.
Anagram Grouping
question = """
Given an array of strings, group the anagrams together in separate arrays.
An anagram is a word or phrase formed by rearranging the letters of another
word or phrase, using all the original letters exactly once.
Example:
$ groupAnagrams(["eat","tea","ten","poop","net","ate"])
$ [["poop"],["net","ten"],["eat","tea","ate"]]
"""
def groupAnagrams(array):
group_hash = {}
for word in array:
chars = []
for char in word:
chars.append(char)
chars.sort()
chars_str = str(chars)
if chars_str not in group_hash:
group_hash[chars_str] = []
group_hash[chars_str].append(word)
# print(group_hash)
groups = []
for group_value in group_hash.values():
groups.append(group_value)
return groups
print(groupAnagrams(["eat","tea","ten","poop","net","ate"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment