Group Anagrams (LeetCode 49): Solution and Explanation

Medium
Array
Hash Table
String
Sorting

Given a list of lowercase strings, group together all strings that are anagrams of one another and return the groups in any order.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A brute force approach compares every string with every other string using an anagram check, then merges matches into groups. That is O(n²) comparisons, each costing O(k) for strings of length k, and the merging bookkeeping is awkward. A better idea is to give every string a signature that is identical for all of its anagrams and different for everything else. Then grouping is just bucketing by signature in a hash map.

The first signature most people think of is the sorted string: "eat", "tea" and "ate" all sort to "aet". That works and costs O(k log k) per string. Because the input uses only the 26 lowercase letters, there is an even cheaper signature: the count of each letter. Two strings are anagrams exactly when their 26 counts match, so a tuple of those counts is a perfect key, and building it takes O(k) time.

The reference solution builds a list of 26 zeros for each string, increments the slot ord(c) - ord('a') for each character, converts the list to a tuple so it can be hashed, and appends the original string to the list stored under that key. A defaultdict(list) removes the need to check whether the key exists yet. At the end, the dictionary's values are exactly the groups.

Approach: Hash map keyed by letter counts

  1. Create ans = collections.defaultdict(list) to map each signature to its group.
  2. For each string s in strs, create count = [0] * 26.
  3. For each character c in s, increment count[ord(c) - ord('a')].
  4. Convert count to a tuple, since lists cannot be dictionary keys, and append s to ans[tuple(count)].
  5. After processing every string, return list(ans.values()).

Step-by-step example

strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
  1. "eat" has one a, one e and one t, so its key has 1 at positions 0, 4 and 19. The map becomes {key_aet: ["eat"]}.
  2. "tea" produces the same counts and joins the same group: ["eat", "tea"].
  3. "tan" has a, n and t, a new key. Group key_ant = ["tan"].
  4. "ate" matches key_aet, making ["eat", "tea", "ate"]. "nat" matches key_ant, making ["tan", "nat"].
  5. "bat" has a, b and t, a third key, so it starts ["bat"].
  6. Return [["eat","tea","ate"], ["tan","nat"], ["bat"]].

Code: Python, Java, C++

1class Solution:
2    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
3        ans = collections.defaultdict(list)
4        for s in strs:
5            count = [0] * 26
6            for c in s:
7                count[ord(c) - ord("a")] += 1
8            ans[tuple(count)].append(s)
9        return list(ans.values())

Time and space complexity

Time

O(n × k)

For each of the n strings we count k characters and then build and hash a 26-element tuple. The tuple work is constant, so the total is O(n × (k + 26)), which simplifies to O(n × k).

Space

O(n × k)

The map stores every input string once across its groups, plus one 26-element key per distinct group.

Other approaches

Sorted string as the key (time O(n × k log k), space O(n × k))

Use ''.join(sorted(s)) as the dictionary key. It is shorter to write and works for any character set, not just lowercase letters, but sorting each string costs O(k log k).

Pairwise anagram checks (time O(n² × k), space O(n × k))

Compare each string against a representative of every existing group. It needs no hashing but grows quadratically with the number of strings and is too slow for large inputs.

Common mistakes

  • Using the count list directly as a dictionary key. Python lists are mutable and unhashable, so you must convert to a tuple first.
  • Building the key by joining counts into a string without a separator. Counts like [1, 11] and [11, 1] both become "111"; use a tuple or put a delimiter between numbers.
  • Assuming the count key works for uppercase or Unicode input. The 26-slot array only covers lowercase English letters; switch to the sorted-string key for other alphabets.
  • Forgetting that the empty string is valid input. Its key is 26 zeros, and all empty strings should end up in one group.

Frequently asked questions

Why use a count array instead of sorting each string?

Counting is O(k) per string while sorting is O(k log k). With long strings the count key is faster, and with only 26 letters the key is a small fixed-size tuple.

What is the time complexity of Group Anagrams?

With the count key it is O(n × k), where n is the number of strings and k the maximum length. With the sorted key it is O(n × k log k).

Does the order of the groups matter?

No. Any order of groups, and any order within each group, is accepted. In Python 3.7 and later, dictionaries keep insertion order, so groups appear in the order their first member was seen.

Can I use a prime number product as the key?

Assigning each letter a prime and multiplying works mathematically, but for long strings the product overflows fixed-size integers in Java or C++. The count tuple is safer.