C++20 sections · 1024 units
Open in Course

Group Anagrams

Grouping pattern

Group words that are anagrams of each other using a map. Sort each word to create a canonical key: map<string, vector> groups; stores words by their sorted form. For each word, compute its sorted version: string key = word; sort(key.begin(), key.end()); groups[key].push_back(word); adds the word to its anagram group.

All anagrams share the same sorted key because they contain the same characters. Iterate over the map to retrieve groups. This runs in O(nklogk)O(n \cdot k \log k) for n words of max length k.