Skip to content
LC-0049 Medium LeetCode

49. Group Anagrams

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 71% Topics: Array, Hash Table, String, Sorting
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n * glogg), g is the max size of groups.
# Space: O(n)

import collections


class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        anagrams_map, result = collections.defaultdict(list), []
        for s in strs:
            sorted_str = ("").join(sorted(s))
            anagrams_map[sorted_str].append(s)
        for anagram in anagrams_map.values():
            anagram.sort()
            result.append(anagram)
        return result


Solution from kamyu104/LeetCode-Solutions · MIT