Created
February 7, 2022 01:58
-
-
Save amarjitdhillon/acecfee74072c79429400c2f95c593cb to your computer and use it in GitHub Desktop.
Group 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
class Solution: | |
def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | |
if len(strs) == 0: | |
return [] | |
c_dict = {} | |
for word in strs: | |
freq_list = [0]*26 | |
for c in word: | |
freq_list[ord(c)-ord('a')] += 1 # increment counter for freq in list | |
freq_list = tuple(freq_list) # as tuple is immutable and can be used as key in dict | |
if freq_list not in c_dict.keys(): | |
c_dict[freq_list] = [word] # add the first word in the list | |
else: | |
c_dict[freq_list].append(word) # add more anagrams to the list | |
return c_dict.values() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment