roadmap/arrays-hashing/Group Anagrams

Group Anagrams

MediumAmazonGoogleFacebookMicrosoftApple
Solve on LeetCode ↗

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

Two strings are anagrams if and only if their sorted versions are identical. Use the sorted string as a HashMap key — all anagrams map to the same key and get grouped together automatically.

Sorted string as key

For each string, sort its characters to get a canonical key. All anagrams produce the same sorted key. Store groups in a HashMap from key → list of strings.

Time
O(n × k log k)
Space
O(n × k)

n strings each of max length k. Sorting each string is O(k log k). HashMap stores all strings.

Python
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
    groups = defaultdict(list)
    for s in strs:
        key = tuple(sorted(s))  # or ''.join(sorted(s))
        groups[key].append(s)
    return list(groups.values())
Empty string is its own group with key ''
Single character strings
All strings are anagrams of each other

What pattern do you think this problem uses?

Progress is saved on this device