DSA Visualizer · 25 visualizationsGroup Anagrams
MediumArrays & Hashing

Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order. Two strings are anagrams if one is a rearrangement of the other's characters.

strs = ["eat", "tea", "tan", "ate", "nat", "bat"]Step 1 of 8
eat
0
tea
1
tan
2
ate
3
nat
4
bat
5
groups
empty

Start with an empty map from each word's sorted letters to the words that share them.

Pythontime O(n · k log k) · space O(n · k)
1def groupAnagrams(strs):
2 groups = {}
3 for s in strs:
4 key = "".join(sorted(s))
5 if key not in groups:
6 groups[key] = []
7 groups[key].append(s)
8 return list(groups.values())
Variables
i—
s—
key—

Problem

Given an array of strings strs, group the anagrams together. You can return the answer in any order. Two strings are anagrams if one is a rearrangement of the other's characters.

Examples

Input: strs = ["eat","tea","tan","ate","nat","bat"]Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Input: strs = [""]Output: [[""]]

Constraints

  • 1 ≤ strs.length ≤ 10⁴
  • 0 ≤ strs[i].length ≤ 100
  • strs[i] consists of lowercase English letters

Intuition

Anagrams share the same letters, so they also share the same sorted form. Use that sorted form as a key and collect each word under it.

Brute force → Optimal

Brute force

For each word, compare its sorted form with every other word's sorted form and merge the matches into groups.

Time O(n² · k log k)Space O(n · k)
Optimal

Sort each word once to build a key, then append the word to the matching bucket in a hash map.

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

Complexity

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

Edge cases

  • A single word, e.g. ["a"], forms one group by itself.
  • Words with repeated letters, e.g. "aab" and "aba", still share the same sorted key.
  • The empty string is its own group when it appears in the input.

Common mistakes

  • Not sorting (or otherwise normalizing) the characters before using them as a key.
  • Creating a fresh list for every word instead of appending to the existing group.
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free