15% off all plans & roadmaps Use code

See plans

Group Anagrams

Updated

TL;DR: Group the strings that are anagrams of each other, in any order. Give every string a canonical key (its sorted letters or its 26 letter counts) and collect strings with the same key in a hash map.

Problem

Given an array of strings strs, group the anagrams together. Two strings are anagrams when one can be rearranged into the other using every letter exactly once. You may return the groups in any order.

Example 1

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation:
- No other string can be rearranged to form "bat".
- "nat" and "tan" are anagrams of each other.
- "ate", "eat" and "tea" are anagrams of each other.

Example 2

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

Example 3

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

Constraints

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

Constraints that matter

  • strs.length up to 10^4 rules out comparing every pair of strings with an expensive check. That is 5 * 10^7 pairs, each costing a sort or a count.
  • Each string has at most 100 characters, so computing a key for one string is cheap: sorting costs about 700 steps and counting costs 100.
  • Only lowercase letters appear, so a fixed array of 26 counts describes any string. That makes an O(k) key possible instead of an O(k log k) sort.
  • Strings can be empty, so the key for the empty string must be valid and must differ from every non-empty key.
  • Group order is free, so you can return groups in the order their first member appeared.

View on LeetCode

Hints

Hint 1

This is a hashing problem built on a frequency map.

Hint 2

Take the first string that is not yet placed in a group.

Solution

Intuition

This is a hashing problem built on a frequency map. Two strings are anagrams exactly when they have the same count of each letter. So you need one value that depends only on those counts and ignores the order of the letters.

Picture sorting words into piles by their Scrabble tile counts. The 26-slot tally sheet is the count array, each slot holds how many of one letter the word uses, and each pile is one hash map bucket.

A value like that is called a canonical key. If every anagram of a word produces the same key, and non-anagrams produce different keys, then grouping becomes a lookup. You compute the key, find its bucket in a hash map, and drop the string in.

The signal to look for is a relation that is symmetric and transitive, such as "is an anagram of". Such a relation splits the input into classes, and each class can be named by one representative value. Whenever you must bucket items by a property that ignores order, think about a key first and comparisons second.

There are two natural keys here. Sorting the letters gives "aet" for "eat", "tea" and "ate". Counting the letters gives the same 26 numbers for all three. Sorting costs O(k log k) per word and counting costs O(k), where k is the word length. Both beat comparing pairs.

Watch the pattern animation

Worked example

Input: strs = ["", "b", "", "b", "bb", "bb", "b"]
Output: [["", ""], ["b", "b", "b"], ["bb", "bb"]]
Explanation: The two empty strings form one group. The three copies of "b" form another, and the two copies of "bb" form a third. "b" and "bb" differ in letter count, so they never share a group. Group order and order inside a group do not matter.

Approach 1: Brute force: compare every pair

Take the first string that is not yet placed in a group. Start a new group with it, then scan every later string and check whether it is an anagram of the first one. If it is, add it to the group and mark it as used.

The anagram check sorts both strings and compares the results. This is the plain version a beginner writes, with a used array so nothing lands in two groups.

Steps

  1. Create a used array of booleans, all false, and an empty result list.
  2. For each index i, skip it if used[i] is true.
  3. Mark i as used and start a group containing strs[i].
  4. For each later index j that is not used, sort both strings and compare them.
  5. If the sorted strings are equal, mark j as used and append strs[j] to the group.
  6. After the inner loop, append the group to the result.
  7. Return the result.

Dry run

Input: ["", "b", "", "b", "bb", "bb", "b"] (indices 0 to 6).

  • i = 0, string "". Scan j = 1..6. Only index 2 ("") matches. Group ["", ""]. Used: 0, 2.
  • i = 1, string "b". Index 3 matches and index 6 matches. Index 4 and 5 ("bb") sort to "bb", not "b". Group ["b", "b", "b"]. Used: 1, 3, 6.
  • i = 2 and i = 3 are already used, so they are skipped.
  • i = 4, string "bb". Index 5 matches. Group ["bb", "bb"].
  • i = 5 and i = 6 are used, so they are skipped.

Result: [["", ""], ["b", "b", "b"], ["bb", "bb"]].

Complexity

TimeO(n^2 * k log k)
SpaceO(n * k)

Let n be the number of strings and k the maximum length. The two nested loops run up to n * (n - 1) / 2 pairs, and each pair sorts two strings in O(k log k). That gives O(n^2 * k log k) time. The used array is O(n), and the result holds every string once, so space is O(n * k) including the output.

PythonTested in our runner

from typing import List

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        n = len(strs)
        used = [False] * n
        result = []
        for i in range(n):
            if used[i]:
                continue
            used[i] = True
            group = [strs[i]]
            for j in range(i + 1, n):
                # re-sort both strings for every pair
                if not used[j] and sorted(strs[i]) == sorted(strs[j]):
                    used[j] = True
                    group.append(strs[j])
            result.append(group)
        return result

Approach 2: Sorted string as hash map key

What's slow: the brute force sorts the same strings again and again, once for every pair they appear in. A string at index 0 gets sorted up to n times. It also scans the whole remaining array to find its group.

The insight that fixes it: sort each string once and use the sorted result as a key. All anagrams share one sorted form, so a hash map from sorted string to list of originals puts each string in its group with one lookup. Each string is processed exactly once.

Steps

  1. Create an empty hash map from string to list of strings.
  2. For each string s, copy its characters and sort them to build key.
  3. Look up key in the map. If it is missing, create an empty list for it.
  4. Append the original string s (not the sorted copy) to that list.
  5. After the loop, collect the map's lists into the result and return them.

Dry run

Input: ["", "b", "", "b", "bb", "bb", "b"].

  • "" sorts to "". Map: {"": [""]}.
  • "b" sorts to "b". Map adds "b": ["b"].
  • "" again. The "" list becomes ["", ""].
  • "b" again. The "b" list becomes ["b", "b"].
  • "bb" sorts to "bb". New entry "bb": ["bb"].
  • "bb" again. That list becomes ["bb", "bb"].
  • "b" last. The "b" list becomes ["b", "b", "b"].

The map holds three lists, which gives [["", ""], ["b", "b", "b"], ["bb", "bb"]].

Complexity

TimeO(n * k log k)
SpaceO(n * k)

Let n be the number of strings and k the maximum length. Each string is sorted once in O(k log k), and hashing a key of length k costs O(k), so each string costs O(k log k) and the loop costs O(n * k log k). The map stores every original string once plus one key per group, which is at most n keys of length k, so space is O(n * k).

PythonTested in our runner

from typing import List

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups = {}
        for s in strs:
            key = "".join(sorted(s))
            if key not in groups:
                groups[key] = []
            groups[key].append(s)
        return list(groups.values())
Hashing - Frequency Map / Counting pattern infographic for Group Anagrams

Solution pattern

Hashing - Frequency Map / Counting

Part of Array/Matrix Manipulation Patterns

Approach 3: Letter-count key hash mapOptimalHashing - Frequency Map / Counting

What's slow: sorting a string of length k costs O(k log k), yet all you need from it is how many times each letter appears. Sorting does more work than the question requires.

The insight that fixes it: count the letters into an array of 26 integers, one slot per letter, in a single O(k) pass. That array is the key. Two strings are anagrams exactly when their count arrays are equal. Turn the array into a hashable key, for example by joining the numbers with a separator, and use the same hash map grouping as before.

The separator matters. Without it, counts like 1 and 11 could blur together in the joined text.

Why it is correct. The count array depends only on the multiset of letters, so every anagram of a word produces the identical array and lands in the same bucket. Two strings with identical arrays have the same number of every letter, so they are anagrams and no anagram is ever missed. The separator keeps the joined text unique for each array, so non-anagrams never share a group.

Steps

  1. Create an empty hash map from key to group index, and an empty list of groups.
  2. For each string s, make an array count of 26 zeros.
  3. For each character c in s, increment count[c - 'a'].
  4. Turn count into a key: join the 26 numbers with a separator such as a comma, or use the array itself where the language allows it.
  5. If the key is new, record the index of a fresh empty group in the map.
  6. Append the original string s to its group.
  7. Return the list of groups.

Dry run

Input: ["", "b", "", "b", "bb", "bb", "b"]. Only the counts for a and b matter here, since every other slot stays 0. Written as a key, "" is 26 zeros, "b" has a 1 in slot 1, and "bb" has a 2 in slot 1.

StepStringCount (a, b, rest 0)Key statusGroups after step
1""a=0, b=0new, group 0[[""]]
2"b"a=0, b=1new, group 1[[""], ["b"]]
3""a=0, b=0seen, group 0[["", ""], ["b"]]
4"b"a=0, b=1seen, group 1[["", ""], ["b", "b"]]
5"bb"a=0, b=2new, group 2[["", ""], ["b", "b"], ["bb"]]
6"bb"a=0, b=2seen, group 2[["", ""], ["b", "b"], ["bb", "bb"]]
7"b"a=0, b=1seen, group 1[["", ""], ["b", "b", "b"], ["bb", "bb"]]

The final list is [["", ""], ["b", "b", "b"], ["bb", "bb"]], which matches the expected output.

Complexity

TimeO(n * (k + 26))
SpaceO(n * k)

Let n be the number of strings and k the maximum length. For each string, counting letters takes O(k), building and hashing the key takes O(26) because the key always has 26 numbers, and the map lookup is O(1) on average. That gives O(n * (k + 26)), which is O(n * k) for practical lengths. The map and groups hold each original string once plus at most n keys of constant size, so space is O(n * k).

PythonTested in our runner

from typing import List

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups = {}
        for s in strs:
            count = [0] * 26
            for ch in s:
                count[ord(ch) - ord('a')] += 1
            key = tuple(count)  # lists are unhashable, tuples are fine
            if key not in groups:
                groups[key] = []
            groups[key].append(s)
        return list(groups.values())

Common mistakes

  • Using the sum of character codes as the key. "ac" and "bb" both sum to 196 but are not anagrams. Use sorted letters or a full count array, which keep all the information.
  • Using a set of characters as the key. "bob" and "bo" give the same set {b, o} but have different counts. The key must record how many times each letter appears.
  • Joining the count array without a separator, such as "".join(map(str, count)). Counts 1 and 11 in neighbouring slots can produce the same text. Join with a comma or a #.
  • Appending the sorted copy, as in groups[key].append(key). The answer needs the original strings. Append s, and use the sorted string only as the key.
  • Looping over a list of existing groups to find where a word belongs. That search is linear in the number of groups and brings back O(n^2) behaviour. Look the key up in a hash map instead.
  • Skipping the empty string or assuming every key is non-empty. An empty string must produce a valid key (empty or 26 zeros) and land in its own group, with other empty strings.

Edge cases

  • [""]: one empty string returns [[""]].
  • ["", ""]: two empty strings are anagrams of each other and return one group [["", ""]].
  • ["a"]: a single word returns one group with that word.
  • All strings identical, such as ["ab", "ab", "ab"]: one group of three. Duplicates are kept, not removed.
  • No two strings are anagrams, such as ["abc", "abd", "ab"]: each string forms its own group, so the result has n groups.
  • Same letters but different lengths, such as ["b", "bb"]: two groups. A key that ignores counts would wrongly merge them.
  • Maximum size, 10^4 strings of length 100: the O(n^2) approach is too slow here, while both hash map approaches finish quickly.

Follow-ups interviewers ask

Can you avoid the O(k log k) sort for each word?
Yes. Count the letters into an array of 26 integers in O(k) and use that array as the key. This is the count-key approach. It works because the alphabet is fixed at 26 lowercase letters.
What if the strings can contain any Unicode characters?
A fixed array of 26 no longer fits. Either sort the characters (code points) and use the sorted string as the key, or build a hash map from character to count and turn it into a sorted list of pairs for the key. Sorting is the simpler fix when the alphabet is large and unknown.
What if the data does not fit in memory?
The key is a function of one string only, so the work splits cleanly. Compute each key while streaming through the data and partition strings by a hash of the key, for example across files or machines. Every anagram group lands in one partition, and you group each partition on its own.

Group Anagrams FAQ

What is the time complexity of Group Anagrams?

With a sorted-string key it is O(n * k log k), where n is the number of strings and k is the longest length. With a 26-letter count key it is O(n * k). The brute force pairwise comparison is O(n^2 * k log k). Space is O(n * k) in all hash map versions.

Why use a hash map for Group Anagrams?

The task is to bucket strings by a shared property, and a hash map finds a bucket by key in O(1) on average. Without it you must compare each string with every group, which costs O(n^2) in the worst case. The key (sorted letters or counts) is what makes anagrams collide on purpose.

Which is better for LeetCode 49, sorting or counting?

Counting is asymptotically faster, O(k) against O(k log k) per word. With k at most 100 and 26 letters, both run well within limits, so either passes. Sorting is shorter to write and works for any alphabet, so it is a good first answer in an interview.

How do I solve Group Anagrams in Python?

Use a dictionary. For each string compute key = "".join(sorted(s)) and append the string to groups[key]. Return list(groups.values()). If you use the count version, use tuple(count) as the key, because lists cannot be dictionary keys.

How do I solve Group Anagrams in Java?

Use a HashMap<String, List<String>> or a map from key to group index. Convert each string to a char array, sort it, and build the key with new String(chars). Note that this problem's starter returns String[][], so convert the lists to arrays at the end.

Can Group Anagrams be solved in O(1) extra space?

No. The output must contain every input string, and the groups are not known until all strings are processed. You need at least O(n * k) space for the result, and the hash map keys add to that. The extra space beyond the output is the keys, which is O(n) keys of constant size in the count version.

Asked at

See which companies ask this — Pro

Practise it