Arrays & Hashing

Hash Map with a Canonical Key

Group Anagrams

1Question

Group Anagrams

MediumLeetCode 49 ↗

You are given an array of strings strs. Group the anagrams together and return the groups. You can return the groups in any order.

Rules

An anagram is a word made by re-arranging the letters of another word, using every letter exactly once. For example, "eat" and "tea" are anagrams. The order of the groups, and the order of the words inside a group, does not matter.

Examples
Example 1
Input: ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

“eat”, “tea” and “ate” use the same letters. “tan” and “nat” use the same letters. “bat” is alone.

Example 2
Input: [""]
Output: [[""]]

An empty string is only an anagram of another empty string. So it forms one group by itself.

Example 3
Input: ["a"]
Output: [["a"]]

One word makes one group.

Constraints

1 ≤ strs.length ≤ 104

Up to 10,000 words. Comparing every pair of words is about 50 million comparisons. We can do it in one pass.

0 ≤ strs[i].length ≤ 100

Each word is short. Sorting one word is cheap, so we can afford to sort every word.

strs[i] has only lowercase English letters

Only 26 possible letters. This also lets us count letters with a fixed array of size 26.

2Hints

Open one hint at a time. Try to think before you open the next one.

3Pattern

Pattern name

Hash Map with a Canonical Key

Give every item a label that is the same for all items in its group. Then group by label.

Two anagrams look different, but they have one thing in common: the same sorted letters. That shared form is called a canonical key. A hash map from key → list of words then does all the grouping for us:

key = sorted(word); groups[key].append(word)

Every word is turned into a key once and added once. We never compare two words directly.

How to spot this pattern

  • You must group items that are “the same” in some way.
  • Items that belong together look different, but can be turned into one identical form (sorted, counted, normalised).
  • The order of the groups in the answer does not matter.
  • You are allowed O(n) extra memory for the map.

4Explanation

The big idea: Walk through the words once with a map called groups (key → list of words). For each word:

Step 1: Make the key

Sort the letters of the word: key = "".join(sorted(word)). For "tea" the key is "aet".

Step 2: Add to its group

Append the word to groups[key]. If the key is new, start a new list.

Why does this work? Two words have the same sorted letters if and only if they are anagrams. So words with the same key are exactly one group.

What is the answer? Each key owns one list. The answer is all the lists: list(groups.values()).

5Brute Force

Compare each word with the groups we already have.

Idea

Keep a list of groups. For each word, look for a group it belongs to:

  • Go through the existing groups one by one.
  • Compare the word with the first word of the group. Are they anagrams?
  • If yes, add the word to that group. If no group matches, start a new group.
Python
def is_anagram(a, b):
    if len(a) != len(b):
        return False

    count = {}
    for ch in a:
        count[ch] = count.get(ch, 0) + 1
    for ch in b:
        if count.get(ch, 0) == 0:
            return False
        count[ch] -= 1

    return True


def group_anagrams_brute(strs):
    groups = []                          # list of lists

    for word in strs:
        placed = False
        for group in groups:
            if is_anagram(word, group[0]):   # compare with the first word of the group
                group.append(word)
                placed = True
                break
        if not placed:
            groups.append([word])        # no match: start a new group

    return groups


print(group_anagrams_brute(["eat", "tea", "tan", "ate", "nat", "bat"]))
# [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

6Optimal Solution

One pass with a hash map from sorted word → list of words.

Python
from collections import defaultdict


def group_anagrams(strs):
    groups = defaultdict(list)           # sorted word -> list of words

    for word in strs:
        key = "".join(sorted(word))      # same key for all anagrams
        groups[key].append(word)         # O(1) to find the group

    return list(groups.values())


print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
# [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

7Time and Space Complexity

Let n be the number of items in the array.

Brute force

Time: O(n² · k)Space: O(n · k)

Optimal (hash map with sorted key)

Time: O(n · k log k)Space: O(n · k)

How big is the difference?

Approximate number of word comparisons or word visits (worst case, k is at most 100):

nBrute force (n²/2)Hash map (n)
104510
1,000499,5001,000
10,000about 50 million10,000

The hash map visits each word once. Even after paying k log k to sort each word, it does far less work for the biggest input.

8Visualization

Try:Use 1 to 8 lowercase words (0 to 6 letters each), separated by commas. Type "" for an empty word.
Current Word-
Key-
Groups-
"eat" "tea" "tan" "ate" "nat" "bat"

Step Analysis

Click "Next" to begin analysis.
Core Logic:
Key: = sorted letters of the word
Key exists: add the word to that group
New key: start a new group