Group Anagrams
Difficulty: Medium
Given a list of strings, group together the strings that are anagrams of each other (same letters, different order).
Return the groups as a list of lists. Each string goes in exactly one group. The groups, and the strings within each group, can be in any order.
Examples
Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output: [["eat","tea","ate"], ["tan","nat"], ["bat"]]
"eat", "tea", and "ate" all use the same three letters. "tan" and "nat" share another set of letters. "bat" doesn't match anything else, so it sits alone in its own group.
Input: strs = [""]
Output: [[""]]
A single empty string just forms its own group.
Input: strs = ["a"]
Output: [["a"]]
Constraints
1 <= strs.length <= 10^4
0 <= strs[i].length <= 100
strs[i] consists of lowercase English letters.
Approach
The direct way takes each string and checks it against every group so far, using a two-string anagram check. That works, but the comparisons add up as the list grows.
A cleaner approach uses the fact that anagrams become the same string when their letters are sorted. That sorted string is a signature shared by every anagram of a word. A hash map from signature to the matching strings groups the whole list in one pass.
Solutions
Brute Force - Compare Against Existing Groups
Check each string against the first string of every group so far, using a letter-count comparison. If it's an anagram, add it to that group. Otherwise, start a new group.
function groupAnagrams(strs) {
const groups = [];
for (const str of strs) {
let placed = false;
for (const group of groups) {
if (isAnagramOf(str, group[0])) {
group.push(str);
placed = true;
break;
}
}
if (!placed) {
groups.push([str]);
}
}
return groups;
}
function isAnagramOf(a, b) {
if (a.length !== b.length) return false;
const counts = {};
for (const ch of a) counts[ch] = (counts[ch] || 0) + 1;
for (const ch of b) {
if (!counts[ch]) return false;
counts[ch]--;
}
return true;
}Time: O(n² · k), where n is the number of strings and k is their max length · Space: O(n · k)
Optimal - Sorted String as Hash Key
Sort each string's letters to build a key. Anagrams always produce the same key. Map each key to the strings that share it, then return the map's values as the groups.
function groupAnagrams(strs) {
const groups = new Map();
for (const str of strs) {
const key = str.split("").sort().join("");
if (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key).push(str);
}
return Array.from(groups.values());
}Time: O(n · k log k), where n is the number of strings and k is their max length · Space: O(n · k)