← Back to Algorithms, page 1

algorithms-0005 · Medium fresher

Group anagrams: given a list of words, group together the words that are anagrams of each other.

Two words are anagrams when they have the same letters with the same counts. Map each word to a canonical key, either its sorted letters or a tuple of 26 letter counts, and collect words with equal keys in a dictionary of lists. Sorting keys cost O(k log k) per word; counting keys cost O(k).

Full answer

Problem

Given words (lowercase English letters), return a list of groups, where each group holds words that are anagrams. Order of groups and of words inside a group does not matter.

Example: ["eat", "tea", "tan", "ate", "nat", "bat"] gives [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]].

Constraints: 0 <= len(words) <= 10^4, each word has length 0 <= k <= 100.

Brute force

Compare each word with every existing group by checking whether they are anagrams (for example by comparing sorted letters). With n words and up to n groups that is O(n^2 x k log k).

Optimal approach

Pick a key that is identical for all anagrams and different otherwise:

  • Sorted key: "".join(sorted(word)). "eat", "tea" and "ate" all become "aet". Cost O(k log k) per word.
  • Count key: a tuple of 26 counts. "eat" becomes (1, 0, 0, 0, 1, 0, ..., 1, ...). Cost O(k) per word plus 26 for the tuple.

Use defaultdict(list) and append each word to groups[key].

Why it works

Anagrams have exactly the same multiset of letters, and both keys encode that multiset precisely, so anagrams share a key and non-anagrams do not. The dictionary does the grouping in one pass.

Complexity

Count key: O(n x k) time, O(n x k) space for the output and keys. Sorted key: O(n x k log k) time.

Code

python
from collections import defaultdict


def group_anagrams(words):
    """Group words that are anagrams. Key = letter counts, O(total characters)."""
    groups = defaultdict(list)
    for w in words:
        counts = [0] * 26
        for ch in w:
            counts[ord(ch) - ord("a")] += 1
        groups[tuple(counts)].append(w)
    return list(groups.values())


def group_anagrams_sorted_key(words):
    """Simpler key: the sorted word. O(n * k log k)."""
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)
    return list(groups.values())


def normalise(groups):
    return sorted(sorted(g) for g in groups)


if __name__ == "__main__":
    words = ["eat", "tea", "tan", "ate", "nat", "bat"]
    expected = [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]
    assert normalise(group_anagrams(words)) == expected
    assert normalise(group_anagrams_sorted_key(words)) == expected
    assert group_anagrams([]) == []
    assert normalise(group_anagrams(["", ""])) == [["", ""]]
    assert normalise(group_anagrams(["ab", "ba", "abc"])) == [["ab", "ba"], ["abc"]]
    print("all tests passed")

Save as a05_group_anagrams.py and run python3 a05_group_anagrams.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty input returns an empty list. Empty strings are anagrams of each other. Words of different lengths can never match. If the alphabet is not limited to a-z (Unicode, uppercase), the count array no longer fits; use the sorted key or a Counter converted to a frozen form such as tuple(sorted(Counter(w).items())).

Pattern

Canonical form plus hashing: transform each item into a normal form so equal items collide in a dictionary. The same idea groups shifted strings, equivalent fractions, or rotations of a word.

python
from collections import defaultdict


def group_anagrams(words):
    """Group words that are anagrams. Key = letter counts, O(total characters)."""
    groups = defaultdict(list)
    for w in words:
        counts = [0] * 26
        for ch in w:
            counts[ord(ch) - ord("a")] += 1
        groups[tuple(counts)].append(w)
    return list(groups.values())


def group_anagrams_sorted_key(words):
    """Simpler key: the sorted word. O(n * k log k)."""
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)
    return list(groups.values())


def normalise(groups):
    return sorted(sorted(g) for g in groups)


if __name__ == "__main__":
    words = ["eat", "tea", "tan", "ate", "nat", "bat"]
    expected = [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]
    assert normalise(group_anagrams(words)) == expected
    assert normalise(group_anagrams_sorted_key(words)) == expected
    assert group_anagrams([]) == []
    assert normalise(group_anagrams(["", ""])) == [["", ""]]
    assert normalise(group_anagrams(["ab", "ba", "abc"])) == [["ab", "ba"], ["abc"]]
    print("all tests passed")

Two solutions: a 26-count key (O(k) per word) and a sorted-string key. A helper normalises group order for testing.

Complexity

Time: O(n * k) with the count key; O(n * k log k) with the sorted key. Space: O(n * k). n is the number of words and k the maximum word length. The count key assumes lowercase a-z.

By level

Fresher: Uses the sorted-word key with a dictionary and explains why anagrams share it. States the complexity in terms of n and k. Should test an empty string and a single word.

Mid: Gives the O(k) count key, compares the two keys and handles alphabet assumptions explicitly. Tests inputs where words share letters but differ in counts, such as "aab" and "abb".

Senior: Discusses scaling to huge inputs with external sorting or map-reduce by key, Unicode normalisation issues, and memory cost of keys. Can estimate memory for 10^5 words and choose a key that keeps it small.

Key points

  • Anagrams share the same letter multiset
  • Use a canonical key: sorted letters or letter counts
  • A dictionary of lists does the grouping in one pass
  • Count key is O(k) per word, sorted key O(k log k)
  • The count key needs a known small alphabet

Common mistakes

  • Using a list as a dictionary key instead of a tuple
  • Comparing every pair of words
  • Assuming only lowercase letters without asking
  • Forgetting empty strings

Follow-ups

  • How would you handle Unicode words?
  • How would you group strings that are rotations of each other?
  • How would you do this for 10^9 words that do not fit in memory?

Tips

  • Name the canonical key idea first
  • Give both key options and their costs
  • Ask about the alphabet

Evaluation rubric

  • Correct grouping with a valid key
  • Correct complexity for the chosen key
  • Handles empty strings and input
  • Discusses alphabet assumptions