Algorithm

Group Anagrams

Arrays & Strings Pattern

Group Anagrams

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

CONSTRAINTS
  • 1 <= strs.length <= 10⁴
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters only
EXAMPLE 1
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Each group holds words made of the exact same letters in the same counts. 'bat' shares its letters with no other word, so it stands alone.
EXAMPLE 2
Input: strs = [""]
Output: [[""]]
The single empty string forms one group by itself; there is nothing else to be an anagram of.
EXAMPLE 3
Input: strs = ["a"]
Output: [["a"]]
One word means one group. Any ordering of the output is accepted.
Does the order of the groups, or of the words within a group, matter?
No. Any ordering of the outer list and of the inner lists is accepted; only the partition into anagram families matters.
Can the input contain empty strings, and how are they grouped?
Yes. Every empty string has the empty key, so all empty strings land in one group together.
Sorted-string key or letter-count key — which should I use?
Both are correct. Sorting is O(K log K) per word and shortest to write; a 26-slot count key is O(K) and faster for long words, but must be encoded with delimiters to avoid collisions.

Grouping anagrams is a bucketing problem. We want to organize a list of strings so that every word made from the same set of characters ends up in the same group.

Pairwise Comparison (O(N² * K))

The most naive way is to compare every word with every other word to check if they are anagrams. For each match, we add the word to the corresponding group. This is extremely slow for large lists.

python
# Theoretical approach:
groups = []
for word in strs:
    found = False
    for group in groups:
        if is_anagram(word, group[0]):
            group.append(word)
            found = True
            break
    if not found: groups.append([word])
Canonical Fingerprints

To group items efficiently, we need a way to make scrambled versions of the same word (like "eat", "tea", "ate") look identical. The core insight is to generate a Canonical Fingerprint (a unique key) for each word. If we sort the letters of "eat", "tea", and "ate", they all become "aet" — our perfect key for a Hash Map.

Hash Map Grouping (O(N * K log K))

We iterate through the list exactly once. For each word, we sort its characters to create a key and store the original word in a Hash Map under that key.

python
groups = {}
for s in strs:
    # Use the sorted string as a unique key
    key = "".join(sorted(s))
    if key not in groups:
        groups[key] = []
    groups[key].append(s)
return list(groups.values())
Worked Example:["eat", "tea", "tan", "ate", "nat"]
0
eat
word
1
tea
2
tan
3
ate
4
nat
We process 'eat'. Its sorted key is 'aet', so we add it to the 'aet' bucket.
0
eat
1
tea
word
2
tan
3
ate
4
nat
We process 'tea'. Its sorted key is also 'aet', so we add it to the same 'aet' bucket.
0
eat
1
tea
2
tan
word
3
ate
4
nat
We process 'tan'. Its sorted key is 'ant', so we create a new 'ant' bucket and add it there.
0
eat
1
tea
2
tan
3
ate
word
4
nat
We process 'ate'. Since its sorted key is 'aet', we group it with 'eat' and 'tea'.
0
eat
1
tea
2
tan
3
ate
4
nat
word
We process 'nat'. Its sorted key is 'ant', so we group it with 'tan'. Grouping is complete.
Interactive Strategy Visualization

anagram grouping

Fingerprinting by Sorted Key
Input List
eat
tea
tan
ate
Map (Key → Group)
Map is empty...
🧪

Ready to group anagrams from the input list.

O(N² × K) Pairwise
O(N × K log K) Sort Key
O(N × K) Count Key