Skip to Content

Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

class Solution:
    def groupAnagrams(self, strs):
        anagram_map = defaultdict(list)
        
        for word in strs:
            sorted_word = ''.join(sorted(word))
            anagram_map[sorted_word].append(word)
        
        return list(anagram_map.values())

In this video instead of using the sorted word, he manually builds up a key based on the counts of the characters in the word. This is fine but there isn't any benefit to doing it this way. It's actually slower.

Posted by Jamie Meyer 20 days ago