Simple Python Solution, 5 Lines Beats ~90%


  • 0
    I
    class Solution:
        def groupAnagrams(self, strs):
            sd = collections.defaultdict(list)
            for s in strs:
                s_ = ''.join(sorted(s))
                sd[s_].append(s)
                
            return [l for k,l in sd.items()]
    

    There are other optimizations people are doing to get around sorting the string for a hash that's consistent regardless of character order, but this solution is sufficiently fast and straightforward. O(n + m log(m) )


Log in to reply
 

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