Last active
November 22, 2021 21:11
-
-
Save les-peters/3c6610495413fc6bb78da67b4a215121 to your computer and use it in GitHub Desktop.
Anagram Grouping
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
| 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