49. Group Anagrams

# Medium

针对这种在顺序上做文章的,首先要进行排序,再做操作

Key idea: hashmap()

Solution:

  1. traverse all elements of strs

  2. sort each word by letters

  3. add to hashmap, the words composed with same letters will be mapped to same key-item

  4. covert to result list

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        d = {}
        for x in strs:
            tmp = sorted(x)
            tmp = "".join(tmp)
            if tmp not in d:
                d[tmp] = [x]
            else:
                d[tmp].append(x)
        
        result = []
        for key in d.keys():
            result.append(d[key])
            
        return result

Time complexity = O(n)O(n) , if sorted() is O(1)O(1) , Space complesity = O(n)O(n)

list.sort() change the list, sorted(list) doesn't change the list.

list.reverse() change the list, reversed(list) doesn't change the list.

sorted(string) converts string to a list.

separator.join(list) means convert list to a string combining by separator. For example, "".join(['a', 'b', 'c']) = "abc".

Last updated