Problem Statement

Group Anagrams

You are given a list of words. Your job is to put the anagrams into the same group. An anagram is a word made by shuffling the letters of another word, using every letter exactly once. For example "eat", "tea", and "ate" are all anagrams of each other because they use the same letters, just in a different order. You can return the groups in any order.

mediumStringHash TableSortingArrays & HashingTime: O(n * k log k) · Space: O(n * k)

Signals to notice

group strings with same charactersanagram groupingcanonical form

Brute force first

Compare every pair of strings for anagram. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Sort each string to get a canonical key, group by key in a hash map. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Trace it on strs=["eat","tea","tan","ate","nat","bat"]

s="eat": key="aet" new -> groups={"aet":["eat"]}
s="tea": key="aet" exists -> groups={"aet":["eat","tea"]}
s="tan": key="ant" new -> groups={"aet":[...],"ant":["tan"]}
s="ate": key="aet" exists -> groups["aet"]=["eat","tea","ate"]
s="nat": key="ant" exists -> groups["ant"]=["tan","nat"]
s="bat": key="abt" new -> groups["abt"]=["bat"]
return values -> [["eat","tea","ate"],["tan","nat"],["bat"]]

What must stay true

Two strings are anagrams if and only if their sorted characters are identical. As long as that statement keeps holding, you can trust the steps built on top of it.

Shape of the loop

groups = empty map
for s in strs:
    key = sorted(s)            # canonical form
    groups[key].append(s)      # bucket by key
return list(groups.values())

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Using frequency counting instead of sorting — both work, but sorting is simpler to implement. The fix is usually to return to the meaning of each move, not just the steps themselves.

Arrays & Hashing Pattern