intermediate · strings · hashing · canonical key · anagrams

Group words that share their letters

Problem

A word game keeps a list of lowercase words. Put words that use exactly the same letters the same number of times (rearrangements of each other) into one group.

Return the groups in the order their first word appears in the list, and keep the words inside each group in list order. A word that is repeated belongs to its group twice.

Constraints

  • 0 ≤ words ≤ 12, each 1 to 8 letters (visualization limit)
  • letters a–z only, words separated by spaces

Examples

"leaf flea tone note fale" → [leaf flea fale] [tone note]

Show the solution

Canonical key in a hash map

Sorting a word's letters forgets their order and keeps their counts, which is exactly the information that decides whether two words are rearrangements.

Why it is correct

Two words are rearrangements of each other if and only if their sorted letters are equal strings, so the map sends two words to the same group exactly when they belong together. A group is created when its key is first seen, so groups appear in order of their first word, and words are appended in list order.

Complexity

Time O(n · L log L) expected, extra space O(n · L). Each of the n words is sorted (O(L log L) for L letters) and hashed (O(L)); the map and the groups store every letter once more.

For contrast: For each word, compare its letter counts with the first word of every existing group. That costs O(n² · L) time and O(n · L) space.

Edge cases

  • No words: no groups.
  • The same word twice: one group with both copies.
  • A word with no rearrangement in the list: a group of one.

Common mistakes

  • Using the sum or product of letter codes as the key: different words can collide.
  • Iterating a hash map to output groups, which loses the order of first appearance in languages where map order is unspecified.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class AnagramGroups
{
    /// <summary>Groups rearrangements of each other, groups in order of first appearance, words in input order. Expected O(n L log L).</summary>
    public static List<List<string>> Group(IEnumerable<string> words)
    {
        var groups = new List<List<string>>();
        var groupOf = new Dictionary<string, int>(); // sorted letters -> index into groups
        foreach (string word in words)
        {
            char[] letters = word.ToCharArray();
            Array.Sort(letters);
            string key = new(letters);
            if (!groupOf.TryGetValue(key, out int g))
            {
                g = groups.Count;
                groupOf[key] = g;
                groups.Add([]);
            }
            groups[g].Add(word);
        }
        return groups;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/AnagramGroups.cs

from collections.abc import Iterable
 
 
def group(words: Iterable[str]) -> list[list[str]]:
    """Groups rearrangements of each other; groups in order of first appearance, words in input order."""
    groups: list[list[str]] = []
    group_of: dict[str, int] = {}  # sorted letters -> index into groups
    for word in words:
        key = "".join(sorted(word))
        if key not in group_of:
            group_of[key] = len(groups)
            groups.append([])
        groups[group_of[key]].append(word)
    return groups

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/anagram_groups.py

package dev.bekadan.dsa.problems;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public final class AnagramGroups {
    private AnagramGroups() {
    }
 
    /** Groups rearrangements of each other; groups in order of first appearance, words in input order. */
    public static List<List<String>> group(List<String> words) {
        List<List<String>> groups = new ArrayList<>();
        Map<String, Integer> groupOf = new HashMap<>(); // sorted letters -> index into groups
        for (String word : words) {
            char[] letters = word.toCharArray();
            Arrays.sort(letters);
            String key = new String(letters);
            Integer g = groupOf.get(key);
            if (g == null) {
                g = groups.size();
                groupOf.put(key, g);
                groups.add(new ArrayList<>());
            }
            groups.get(g).add(word);
        }
        return groups;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/AnagramGroups.java

#pragma once
 
#include <algorithm>
#include <string>
#include <unordered_map>
#include <vector>
 
namespace bekadan::dsa::problems {
 
// Groups rearrangements of each other; groups in order of first appearance, words in input order.
inline std::vector<std::vector<std::string>> anagram_groups(const std::vector<std::string>& words) {
    std::vector<std::vector<std::string>> groups;
    std::unordered_map<std::string, std::size_t> group_of;  // sorted letters -> index into groups
    for (const auto& word : words) {
        std::string key = word;
        std::ranges::sort(key);
        auto [it, inserted] = group_of.try_emplace(key, groups.size());
        if (inserted) groups.emplace_back();
        groups[it->second].push_back(word);
    }
    return groups;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/anagram_groups.hpp