class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
...
1. Scenarios
- Input:
strs = ["eat","tea","tan","ate","nat","bat"]
- Output:
[["bat"],["nat","tan"],["ate","eat","tea"]]
- Output:
- Input:
strs = [""]
- Output:
[[""]]
- Output:
- Input:
strs = ["a"]
- Output:
[["a"]]
- Output:
2. Solution Template:
2.1 Scenario 1 Test:
- Input:
strs = ["eat","tea","tan","ate","nat","bat"]
- Output:
[["bat"],["nat","tan"],["ate","eat","tea"]]
- Output:
= ["eat","tea","tan","ate","nat","bat"]
strs = {}
seen_dict
for str_item in strs:
= str_item
str_item = sorted(str_item)
sorted_str_list print(f"pre-sort: {str_item}")
= ''.join(sorted_str_list)
sorted_str print(f"post-sort: {sorted_str}")
= sorted_str
sorted_str_dkey if sorted_str_dkey not in seen_dict:
= [str_item] # create dict entrant
seen_dict[sorted_str] else:
# retriev dict entrant
seen_dict[sorted_str].append(str_item) print(seen_dict)
print()
# [values for values in seen_dict.values()]
*seen_dict.values()] [
pre-sort: eat
post-sort: aet
{'aet': ['eat']}
pre-sort: tea
post-sort: aet
{'aet': ['eat', 'tea']}
pre-sort: tan
post-sort: ant
{'aet': ['eat', 'tea'], 'ant': ['tan']}
pre-sort: ate
post-sort: aet
{'aet': ['eat', 'tea', 'ate'], 'ant': ['tan']}
pre-sort: nat
post-sort: ant
{'aet': ['eat', 'tea', 'ate'], 'ant': ['tan', 'nat']}
pre-sort: bat
post-sort: abt
{'aet': ['eat', 'tea', 'ate'], 'ant': ['tan', 'nat'], 'abt': ['bat']}
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
2.2 Adapt to Template
from typing import List
2.3 Working Easy-To-Understand Version
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
# strs = ["eat","tea","tan","ate","nat","bat"]
= {}
seen_dict
for str_item in strs:
= str_item
pre_sorted_str = sorted(pre_sorted_str)
sorted_str_list # print(f"pre-sort: {pre_sorted_str}")
= ''.join(sorted_str_list)
sorted_str # print(f"post-sort: {sorted_str}")
= sorted_str
sorted_str_dkey if sorted_str_dkey not in seen_dict:
= [pre_sorted_str] # create dict entrant
seen_dict[sorted_str] else:
# retriev dict entrant
seen_dict[sorted_str].append(pre_sorted_str) # print(seen_dict)
# print()
# [values for values in seen_dict.values()]
return [*seen_dict.values()]
= ["eat","tea","tan","ate","nat","bat"]
strs = Solution()
soln soln.groupAnagrams(strs)
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
2.4 Working Less-Lines Version
Same as 2.3 but less new variables
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
= {}
seen_dict for str_item in strs:
= ''.join(sorted(str_item))
sorted_str if ''.join(sorted(str_item)) not in seen_dict:
= [str_item] # create dict entrant
seen_dict[sorted_str] else:
# retriev dict entrant
seen_dict[sorted_str].append(str_item) return [*seen_dict.values()]
= ["eat","tea","tan","ate","nat","bat"]
strs = Solution()
soln soln.groupAnagrams(strs)
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]