49. Group Anagrams

Description

See: https://leetcode.com/problems/group-anagrams/

Solution

When dealing with anagrams, sort the word. Anagram strings will be the same after sorting.

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        anagrams = defaultdict(list)
        for word in strs:
            key = "".join(sorted(list(word)))
            anagrams[key].append(word)
        
        return anagrams.values()

Last updated