Skip to main content
04

Group Anagrams

Mediumhash mapstrings

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Arrays & HashingRead the beginner guide

Given an array of strings strs, group the anagrams together. Return the groups in any order, and the strings inside each group in any order.

Understand the problem

Anagrams are words made of exactly the same letters, the same number of times, just in a different order: eat, tea and ate are all anagrams of each other. (If this is new, solve Valid Anagram first: it checks just two words.)

Here, instead of comparing two words, you get a whole list. Your job is to sort the words into piles, where every pile holds words that are anagrams of each other. A word with no anagram partner gets a pile of its own.

Example 1

text
Input:  strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output: [["bat"], ["nat", "tan"], ["ate", "eat", "tea"]]
  • eat, tea, ate all use one a, one e, one t, so they share a pile.
  • tan and nat both use one a, one n, one t.
  • bat has no anagram in the list, so it's alone.

Example 2

text
Input:  strs = [""]
Output: [[""]]

One empty string makes one pile.

Example 3

text
Input:  strs = ["a"]
Output: [["a"]]

Constraints

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] contains lowercase English letters only.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Give every word a "label" that all of its anagrams share, then use a hash map to put words with the same label into the same pile.

    The naive approach (and why it's slow)

    Take each word and compare it against every pile so far using the Valid Anagram check. With n words, that's up to n × n / 2 comparisons, about O(n²), plus the cost of each comparison. For 10,000 words, that's tens of millions of checks.

    The key insight

    We don't need to compare words with each other at all. If we can compute a key from a single word, such that:

    • all anagrams get the same key, and
    • non-anagrams get different keys,

    then grouping is just "put each word in the bucket for its key". A hash map from key to list of words does that in one pass.

    What's a good key? Sort the word's letters. Anagrams have the same letters, so sorting puts them in the same order:

    text
    "eat" → "aet"
    "tea" → "aet"
    "ate" → "aet"
    "tan" → "ant"

    Step by step

    strs = ["eat", "tea", "tan", "ate", "nat", "bat"]:

    WordKey (sorted letters)Map afterwards
    eataetaet: [eat]
    teaaetaet: [eat, tea]
    tanantaet: [eat, tea], ant: [tan]
    ateaetaet: [eat, tea, ate], ant: [tan]
    natantaet: [eat, tea, ate], ant: [tan, nat]
    batabtaet: [eat, tea, ate], ant: [tan, nat], abt: [bat]

    The answer is the map's three lists.

    A faster key: letter counts

    Sorting a word of length k costs k log k. The reference code below uses a key that only costs k: count each letter into 26 slots (one per letter a–z) and turn the counts into a string.

    text
    "eat" → a:1, e:1, t:1 → "1,0,0,0,1,0,...,1,..."

    Anagrams have identical counts, so they get identical keys. For short words both keys are fine; in an interview, start with the sorted key (easiest to explain), then mention the count key as an improvement.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    With n words of length up to k:

    • Time: O(n · k log k) with the sorted key, O(n · k) with the count key. Either way we touch each word once.
    • Memory: O(n · k), since the map holds every word.

    Common mistakes

    • Using an array as a Map key in JavaScript. Two arrays with the same contents are still different objects, so map.get([1, 2]) never finds [1, 2]. Turn the counts into a string first.
    • Joining counts without a separator. Counts [1, 11] and [11, 1] both become "111". Join with a comma ("1,11" vs "11,1") so they stay different.
    • In Python, a list can't be a dict key, but a tuple can: tuple(counts).

    Reference solution

    js
    /**
     * @param {string[]} strs
     * @return {string[][]}
     */
    export default function groupAnagrams(strs) {
      // key -> every word that has that key (one "pile" per key)
      const groups = new Map()
      for (const str of strs) {
        // Count each letter: counts[0] is 'a', counts[1] is 'b', ... counts[25] is 'z'.
        const counts = new Array(26).fill(0)
        for (const char of str) counts[char.charCodeAt(0) - 97]++ // 97 is the code of 'a'
        // Anagrams have identical counts, so they get identical keys.
        // Join with commas so [1, 11] and [11, 1] don't both become "111".
        const key = counts.join(',')
        if (!groups.has(key)) groups.set(key, [])
        groups.get(key).push(str)
      }
      // Each value in the map is one pile of anagrams.
      return [...groups.values()]
    }
    ts
    export default function groupAnagrams(strs: string[]): string[][] {
      // key -> every word that has that key (one "pile" per key)
      const groups = new Map<string, string[]>()
      for (const str of strs) {
        // Count each letter: counts[0] is 'a', counts[1] is 'b', ... counts[25] is 'z'.
        const counts = new Array<number>(26).fill(0)
        for (const char of str) counts[char.charCodeAt(0) - 97]++ // 97 is the code of 'a'
        // Anagrams have identical counts, so they get identical keys.
        // Join with commas so [1, 11] and [11, 1] don't both become "111".
        const key = counts.join(',')
        const group = groups.get(key)
        if (group) group.push(str)
        else groups.set(key, [str])
      }
      // Each value in the map is one pile of anagrams.
      return [...groups.values()]
    }
    python
    from collections import defaultdict
    
    
    def group_anagrams(strs: list[str]) -> list[list[str]]:
        # key -> every word that has that key. defaultdict(list) starts each new key with [].
        groups = defaultdict(list)
        for s in strs:
            # Count each letter: counts[0] is 'a', counts[1] is 'b', ... counts[25] is 'z'.
            counts = [0] * 26
            for char in s:
                counts[ord(char) - ord("a")] += 1
            # Anagrams have identical counts. A list can't be a dict key, but a tuple can.
            groups[tuple(counts)].append(s)
        # Each value in the dict is one pile of anagrams.
        return list(groups.values())