Group Anagrams

Given an array of strings, group anagrams together.

For example, given:["eat", "tea", "tan", "ate", "nat", "bat"], Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:All inputs will be in lower-case.

class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """

        if not strs:
            return []

        #groupedList = []
        dict = {}
        for elem in strs:
            # sort complexity = m log m, where m is the longest string in strs
            x = ''.join(sorted(elem))
            #print 'sorted elem: ', x

            if x not in dict:
                dict[x] = [elem]
            else:
                dict[x] += [elem]

        return dict.values()

        # Total complexity = n * m log m


        '''
        for k,v in dict.iteritems():
            groupedList += [v]

        return groupedList
        '''

Last updated

Was this helpful?