Group Anagrams in Python

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        # Step 1: Initialize a dictionary to group anagrams
        # The keys are sorted tuples of characters, and the values are lists of strings
        anagrams = {}

        # Step 2: Iterate over each string in the input list
        for s in strs:
            # Sort the string and convert it to a tuple to make it hashable (can be used as a dictionary key)
            sorted_tuple = tuple(sorted(s))

            # Step 3: Group anagrams by adding the string to the correct list in the dictionary
            if sorted_tuple in anagrams:
                anagrams[sorted_tuple].append(s)
            else:
                anagrams[sorted_tuple] = [s]

        # Step 4: Return grouped anagrams by extracting all the lists from the dictionary
        return list(anagrams.values())

PrevNext