Given a sequence of words, print all anagrams together

Pattern: Anagrams

medium

Anagrams share the same sorted letters, so use the sorted word as a key in a map from key to group. One pass over the words fills the groups.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given a list of words, group together the words that are anagrams of each other. For example, ["cat", "dog", "tac", "god", "act"] gives [["cat", "tac", "act"], ["dog", "god"]].

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet (LeetCode's Group Anagrams is the same idea). The function name groupAnagrams and the output order are this guide's own: groups appear in the order their first word appears, and words keep their input order inside each group.

Think first

  • What do two anagrams have in common that you can compute from each word alone?
  • How do you collect words with the same key?
  • How do you keep the groups in the order they first appear?

Hints

    Brute force, and why it fails

    Compare every pair of words with an anagram check and merge groups: O(n² × k). Keys in a hash map make it O(n × k log k) for n words of length up to k.

    The key insight

    A canonical form (here, the sorted letters) turns "is this an anagram of that" into "do they have the same key", which a hash map answers in O(1).

    Dry run

    cat0 
    dog1 
    tac2 
    god3 
    act4 
    keysact, dgo, act, dgo, act

    words = cat, dog, tac, god, act. Each word's key is its letters sorted.

    Step 1 of 4

    The plan

    groups = empty insertion-ordered map
    for each word w:
        key = sorted letters of w
        append w to groups[key] (creating it if new)
    return the lists in groups, in order
    

    Complexity

    Time
    O(n × k log k)
    Space
    O(n × k)

    Each of the n words is sorted, at O(k log k). The map stores every word once.

    Edge cases

    • One word: one group.
    • No anagrams at all: every word is its own group.
    • Repeated words, as in ["ab", "ba", "ab"]: both copies go in the same group.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<List<String>> groupAnagrams(String[] words) {
            Map<String, List<String>> groups = new LinkedHashMap<>();   // keeps groups in order of first appearance
            for (String w : words) {
                char[] key = w.toCharArray();
                Arrays.sort(key);                    // anagrams share the same sorted letters
                groups.computeIfAbsent(new String(key), k -> new ArrayList<>()).add(w);
            }
            return new ArrayList<>(groups.values());
        }
    }

    C++

    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& words) {
            unordered_map<string, int> where;        // sorted letters -> index of its group
            vector<vector<string>> groups;           // in order of first appearance
            for (const string& w : words) {
                string key = w;
                sort(key.begin(), key.end());        // anagrams share the same sorted letters
                auto it = where.find(key);
                if (it == where.end()) {
                    where[key] = static_cast<int>(groups.size());
                    groups.push_back({w});
                } else {
                    groups[it->second].push_back(w);
                }
            }
            return groups;
        }
    };

    Python

    class Solution:
        def groupAnagrams(self, words: list[str]) -> list[list[str]]:
            groups = {}                              # dicts keep insertion order: groups in order of first appearance
            for w in words:
                key = "".join(sorted(w))             # anagrams share the same sorted letters
                groups.setdefault(key, []).append(w)
            return list(groups.values())

    Common mistakes

    • Using an unordered hash map and then expecting a fixed group order.
    • Using a set of letters as the key, which mixes up "aab" and "abb".
    • Sorting the words themselves in place, which loses the original spellings.

    Similar problems