LeetCode 5: 49 - Group Anagrams

Group Anagrams
leetcode
Author

Tony Phung

Published

January 13, 2025

1. Scenarios

  • Input: strs = ["eat","tea","tan","ate","nat","bat"]
    • Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
  • Input: strs = [""]
    • Output: [[""]]
  • Input: strs = ["a"]
    • Output: [["a"]]

2. Solution Template:

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        ...

2.1 Scenario 1 Test:

  • Input: strs = ["eat","tea","tan","ate","nat","bat"]
    • Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
strs = ["eat","tea","tan","ate","nat","bat"]
seen_dict = {}

for str_item in strs:
    str_item = str_item
    sorted_str_list = sorted(str_item)
    print(f"pre-sort: {str_item}")
    sorted_str = ''.join(sorted_str_list)
    print(f"post-sort: {sorted_str}")
    sorted_str_dkey = sorted_str
    if sorted_str_dkey not in seen_dict:
        seen_dict[sorted_str] = [str_item]    # create dict entrant
    else: 
        seen_dict[sorted_str].append(str_item) # retriev dict entrant
    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:
            pre_sorted_str = str_item
            sorted_str_list = sorted(pre_sorted_str)
            # print(f"pre-sort: {pre_sorted_str}")
            sorted_str = ''.join(sorted_str_list)
            # print(f"post-sort: {sorted_str}")
            sorted_str_dkey = sorted_str
            if sorted_str_dkey not in seen_dict:
                seen_dict[sorted_str] = [pre_sorted_str]    # create dict entrant
            else: 
                seen_dict[sorted_str].append(pre_sorted_str) # retriev dict entrant
            # print(seen_dict)
            # print()    
        # [values for values in seen_dict.values()]
        return [*seen_dict.values()]
strs = ["eat","tea","tan","ate","nat","bat"]
soln = Solution()
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:
            sorted_str = ''.join(sorted(str_item))
            if ''.join(sorted(str_item)) not in seen_dict:
                seen_dict[sorted_str] = [str_item]    # create dict entrant
            else: 
                seen_dict[sorted_str].append(str_item) # retriev dict entrant
        return [*seen_dict.values()]
strs = ["eat","tea","tan","ate","nat","bat"]
soln = Solution()
soln.groupAnagrams(strs)
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

3. LeetCode: Submission Results