Python solution with detailed explanation


  • 0
    G

    Solution

    Group Anagrams https://leetcode.com/problems/anagrams/

    Algorithm

    • All anagrams, when sorted, must be equal. Use this property to build a signature.
    from collections import defaultdict
    class Solution(object):
        def groupAnagrams(self, strs):
            """
            :type strs: List[str]
            :rtype: List[List[str]]
            """
            cache = defaultdict(list)
            for s in strs:
                sign = "".join(sorted(s))
                cache[sign].append(s)
            return cache.values()
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.