Group Anagrams

Group strings that are anagrams of each other.

Pattern

Hash Map Grouping

This problem follows the Hash Map Grouping pattern, commonly found in the Arrays & Hashing category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Sort each string and use as key. Group by sorted key in a hash map.

Key Insight

Anagrams produce the same string when sorted — use sorted characters as the hash map key to group them automatically.

Step-by-step

  1. 1Create an empty hash map (sorted_string -> list of strings)
  2. 2For each string, sort its characters to create a key
  3. 3Append the original string to the list at that key
  4. 4Return all the lists from the hash map

Pseudocode

groups = defaultdict(list)
for s in strs:
    key = ''.join(sorted(s))
    groups[key].append(s)
return list(groups.values())
Complexity Analysis

Time Complexity

O(n * k log k)

Space Complexity

O(n * k)
More Arrays & Hashing Problems

Master this pattern with YeetCode

Practice Group Anagrams and similar Arrays & Hashing problems with flashcards. Build pattern recognition through active recall.

Practice this problem