Home
DSA Patterns
Hash Map
Group Anagrams
Group Anagrams (LeetCode 49)
Group Anagrams (LeetCode 49): group words that are anagrams of each other, using each word's sorted letters as a hash map key.
Problem Understanding
Group Anagrams: given an array of strings strs, group the words that are anagrams of each other. The groups, and the words inside them, may be returned in any order.
Example: ["eat", "tea", "tan", "ate", "nat", "bat"] returns [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]].
Attempt 1: Compare Every Pair
For each word not yet grouped, compare it with every later word using an anagram check and pull the matches into its group. That is O(n²) anagram checks. The pairwise comparison is the waste: if each word could be turned into a label that all of its anagrams share, words could be sorted into buckets directly.
The Intuition: A Key Every Anagram Shares
Sort a word's letters and every anagram of it produces the same string: "eat", "tea" and "ate" all sort to "aet". Use that string as a hash map key:
- For each word, compute
key = sorted(word). - If
keyis new, start an empty list for it. - Append the word to
key's list.
One pass, no pairwise comparisons: the map does the matching. It is the same counting idea as Valid Anagram, turned into a key.
Group Anagrams Visualization
["eat", "tea", "tan", "ate", "nat", "bat"]
START
groups (key → words)
empty
Key
:
Groups
0
groups starts empty: each key will map to the list of words that share it
Next
"eat" sorts to "aet": every anagram of "eat" sorts to the same key
Words
The words run along the top with each one's sorted key under it. Below them, the map: one row per key, collecting its words as they arrive. Watch "tea" and "ate" land in the row "eat" started.
Group Anagrams Dry Run
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
| Word | Key | New key? | Map after |
|---|---|---|---|
eat |
aet |
yes | aet: [eat] |
tea |
aet |
no | aet: [eat, tea] |
tan |
ant |
yes | aet: [eat, tea], ant: [tan] |
ate |
aet |
no | aet: [eat, tea, ate], ant: [tan] |
nat |
ant |
no | aet: [eat, tea, ate], ant: [tan, nat] |
bat |
abt |
yes | …, abt: [bat] |
Return the three lists.
Group Anagrams LeetCode Solution
A hash map from sorted letters to the list of words.
Group Anagrams Code
1var groupAnagrams = function(strs) {2 const groups = new Map();3 for (const word of strs) {4 const key = [...word].sort().join('');5 if (!groups.has(key)) {6 groups.set(key, []);7 }8 groups.get(key).push(word);9 }10 return [...groups.values()];11};
Group Anagrams in Python, Java, C++, TypeScript and C
Group Anagrams in Python
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = {}
for word in strs:
key = ''.join(sorted(word))
if key not in groups:
groups[key] = []
groups[key].append(word)
return list(groups.values())Group Anagrams in Java
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> groups = new HashMap<>();
for (String word : strs) {
char[] chars = word.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
if (!groups.containsKey(key)) {
groups.put(key, new ArrayList<>());
}
groups.get(key).add(word);
}
return new ArrayList<>(groups.values());
}
}Group Anagrams in C++
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> groups;
for (const string& word : strs) {
string key = word;
sort(key.begin(), key.end());
groups[key].push_back(word);
}
vector<vector<string>> result;
for (auto& [key, words] : groups) {
result.push_back(words);
}
return result;
}
};Group Anagrams in TypeScript
function groupAnagrams(strs: string[]): string[][] {
const groups = new Map<string, string[]>();
for (const word of strs) {
const key = [...word].sort().join('');
if (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key)!.push(word);
}
return [...groups.values()];
}Group Anagrams in C
typedef struct {
char *key; // the word's letters, sorted
int group; // its group's index in the result
UT_hash_handle hh; // uthash.h, available on LeetCode
} Entry;
static int cmp(const void *a, const void *b) { return *(const char *)a - *(const char *)b; }
char*** groupAnagrams(char** strs, int strsSize, int* returnSize, int** returnColumnSizes) {
Entry *groups = NULL, *e;
char ***result = malloc(strsSize * sizeof(char **));
*returnColumnSizes = calloc(strsSize, sizeof(int));
*returnSize = 0;
for (int i = 0; i < strsSize; i++) {
char *key = strdup(strs[i]);
qsort(key, strlen(key), 1, cmp);
HASH_FIND_STR(groups, key, e);
if (!e) {
e = malloc(sizeof(Entry));
e->key = key;
e->group = (*returnSize)++;
HASH_ADD_KEYPTR(hh, groups, e->key, strlen(e->key), e);
result[e->group] = malloc(strsSize * sizeof(char *));
} else {
free(key);
}
result[e->group][(*returnColumnSizes)[e->group]++] = strs[i];
}
return result;
}Edge Cases & Common Mistakes
- One word, or an empty string: one group.
""sorts to"", a valid key. - Duplicate words: they are anagrams of each other and share a group.
- Using a key that is not order-free: the raw word, or its first letter, splits anagrams apart.
- Comparing by letter set instead of letter counts:
"aab"and"abb"have the same set of letters but are not anagrams: sorting (or full counts) tells them apart.
Summary
When items must be grouped by an equivalence, give every item a key that all equivalent items share, and let a hash map collect them. For anagrams, the key is the sorted letters.
More practice: DSA interview questions with answers · patterns cheat sheet
