Group anagrams

Group words that are anagrams of each other. Sorting each word's letters gives a key that every anagram shares.

Time O(n * w log w)Space O(n * w)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Two words are anagrams exactly when sorting their letters gives the same string. That sorted string is a perfect dictionary key: every word that produces it belongs in the same group, so one pass with a Dictionary<string, List<string>> does all the grouping.

Code

public static List<List<string>> GroupAnagrams(string[] words) {
    var groups = new Dictionary<string, List<string>>();
    foreach (string w in words) {
        var key = new string(w.OrderBy(c => c).ToArray());
        if (!groups.TryGetValue(key, out var list))
            groups[key] = list = new List<string>();
        list.Add(w);
    }
    return groups.Values.ToList();
}
static List<List<String>> groupAnagrams(String[] words) {
    Map<String, List<String>> groups = new HashMap<>();
    for (String w : words) {
        char[] cs = w.toCharArray(); Arrays.sort(cs); String key = new String(cs);
        if (!groups.containsKey(key))
            groups.put(key, new ArrayList<>());
        groups.get(key).add(w);
    }
    return new ArrayList<>(groups.values());
}
vector<vector<string>> groupAnagrams(const vector<string>& words) {
    unordered_map<string, vector<string>> groups;
    for (const string& w : words) {
        string key = w; sort(key.begin(), key.end());
        if (!groups.count(key))
            groups[key] = {};
        groups[key].push_back(w);
    }
    vector<vector<string>> res; for (auto& g : groups) res.push_back(g.second); return res;
}
def group_anagrams(words: list[str]) -> list[list[str]]:
    groups = {}
    for w in words:
        key = "".join(sorted(w))
        if key not in groups:
            groups[key] = []
        groups[key].append(w)
    return list(groups.values())

Tips

In the .NET library

The key never has to be meaningful on its own - it only has to be identical for words that belong together, and different for words that do not. That is the whole job of a hash key.