Group Anagrams
Medium
Topics
Given an array of strings strs, group the anagrams together. Return the groups in any order.
Example 1
Words sharing a shade are anagrams.
Each chip is one input word; shades mark the groups.
Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2
Input: strs = [""] Output: [[""]]
Constraints
- 1 <= strs.length <= 10^4
- 0 <= strs[i].length <= 100
- strs[i] consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Two words are anagrams exactly when their sorted letters match. Use that sorted form as a hash-map key and bucket words together.
Approach
- For each word, compute a canonical key (sorted characters or a 26-length count).
- Append the word to the list under that key.
- Return the map values.
Dry Run
["eat", "tea", "tan", "ate", "nat", "bat"]
eat -> key "aet" bucket [eat]
tea -> key "aet" bucket [eat, tea]
tan -> key "ant" bucket [tan]
ate -> key "aet" bucket [eat, tea, ate]
nat -> key "ant" bucket [tan, nat]
bat -> key "abt" bucket [bat]
answer [eat, tea, ate] | [tan, nat] | [bat]
The key is the SORTED STRING, which is a canonical form: two words are anagrams
exactly when they sort to the same thing, so one hash lookup replaces any pairwise
comparison.
It has to preserve multiplicity. Key on the set of distinct letters instead and
["a", "aaa", "aa"] collapses into a single group, when none of the three are
anagrams of each other.
A character-count tuple works as a key too and is O(k) per word rather than
O(k log k). Sorting is chosen here for how short it is, which is worth saying out
loud rather than defending as optimal.Complexity
- Time — O(n * k log k): sorting each of n words of length up to k.
- Space — O(n * k): storing all words in the map.
Common Pitfalls
- The key is the sorted string, not the set of letters. A set loses multiplicity, so
aandaaacollapse into one group when they are not anagrams. - A character-count tuple works as a key too and is O(n) rather than O(n log n) per word. Sorting is chosen for how short it is, which is worth saying out loud rather than defending as optimal.
Full Solution — all languages
class Solution:
def groupAnagrams(self, strs):
groups={}
for w in strs:
key=''.join(sorted(w))
groups.setdefault(key,[]).append(w)
return list(groups.values())import java.util.*;
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> groups=new HashMap<>();
for(String w:strs) {
char[] c=w.toCharArray();
Arrays.sort(c);
String key=new String(c);
groups.computeIfAbsent(key,z->new ArrayList<>()).add(w);
}
return new ArrayList<>(groups.values());
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string,vector<string>> groups;
for(auto& w:strs) {
string key=w;
sort(key.begin(),key.end());
groups[key].push_back(w);
}
vector<vector<string>> res;
for(auto& kv:groups)res.push_back(kv.second);
return res;
}
};/**
* @param {string[]} strs
* @return {string[][]}
*/ var groupAnagrams = function(strs) {
const groups={};
for(const w of strs) {
const key=w.split('').sort().join('');
(groups[key]=groups[key]||[]).push(w);
}
return Object.keys(groups).map(k=>groups[k]);
};