Group Anagrams [Python Algorithm]
Second post in the series. Two Sum was about remembering where you saw something. This one is about deciding what counts as the same thing.
Problem
Given a list of strings, group the anagrams together. Return the groups in any order.
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
[["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]Anagrams are words made of the same letters in the same quantities. eat, tea, and ate all use one a, one e, one t.
“Any order” means the grader doesn’t care about the order of the groups or the order inside them. [["bat"], ["tan","nat"], ["eat","tea","ate"]] is equally correct.
Brute Force
Compare every word against every other word:
def group_anagrams(strs):
groups = []
used = [False] * len(strs)
for i in range(len(strs)):
if used[i]:
continue
group = [strs[i]]
used[i] = True
for j in range(i + 1, len(strs)):
if not used[j] and sorted(strs[i]) == sorted(strs[j]):
group.append(strs[j])
used[j] = True
groups.append(group)
return groupsIt works, but look at the bookkeeping. You need a used array so words don't land in two groups, and you're re-sorting the same word over and over inside the inner loop.
Time: O(n² · k log k) where n is the number of words and k is the average word length.
Key Insight
The brute force asks “is word A an anagram of word B?” for every pair. That’s the wrong question, because it’s still pairwise.
Better question: what is this word’s group name?
Sorting gives you one, for free:
sorted("eat") -> ['a', 'e', 't']
sorted("tea") -> ['a', 'e', 't']
sorted("ate") -> ['a', 'e', 't']Every anagram of a word sorts to the same sequence. So sorting turns a comparison problem into a labeling problem. Instead of checking words against each other, you compute one label per word and let words with matching labels fall into the same bucket.
That’s a dictionary. The label is the key, the group is the value.
Solution
def group_anagrams(strs):
groups = {}
for word in strs:
key = "".join(sorted(word))
if key not in groups:
groups[key] = []
groups[key].append(word)
return list(groups.values())Watching groups fill up:
"eat" key="aet" new key -> {"aet": ["eat"]}
"tea" key="aet" exists -> {"aet": ["eat", "tea"]}
"tan" key="ant" new key -> {"aet": [...], "ant": ["tan"]}
"ate" key="aet" exists -> {"aet": ["eat", "tea", "ate"], ...}
"nat" key="ant" exists -> {..., "ant": ["tan", "nat"]}
"bat" key="abt" new key -> {..., "abt": ["bat"]}At the end, the keys have done their job and you only want the buckets, so .values() pulls them out. It returns a view object rather than a list, which is why it's wrapped in list().
Complexity
Time: O(n · k log k). One pass over n words, and sorting each k-length word costs k log k.
Get Daniel (Heedong) Jang’s stories in your inbox
Join Medium for free to get updates from this writer.
Space: O(n · k). Every word ends up stored in the dictionary.
Compared to the brute force, the pairwise comparison collapses into a single pass. The sorting cost per word doesn’t change; what changes is that you do it once per word instead of once per pair.
Pitfalls
Dictionaries don’t have .append(). This was my first attempt:
groups = {}
for word in strs:
groups.append(word) # AttributeErrorappend is a list method. A dictionary has no "end" to append to, because entries are stored under labels rather than in sequence. You add to a dictionary by naming the slot: groups[key] = value.
groups.append(word) and groups[key].append(word) are different calls. Once the pitfall above clicked, this one still took a moment. In the working solution, append is being called on groups[key], which is a list, not on groups, which is a dictionary. The dictionary holds lists; the append happens one level down.
You can’t append to a bucket that doesn’t exist yet. The first time you see "aet" there's nothing there to append to, so the empty list has to be created first:
if key not in groups:
groups[key] = []
groups[key].append(word)Forgetting sorted and keeping join. My submission had this:
key = "".join(word) # returns "eat" unchanged"".join() glues a sequence of characters back into a string. On its own it's a no-op, so every word became its own key and nothing grouped. The sorting is what makes anagrams collide; the join is only there because sorted() hands back a list, and lists can't be dictionary keys.
That last part is worth stating plainly, because it explains why the line looks convoluted:
sorted("eat") # ['a', 'e', 't'] a list, unusable as a key
"".join(sorted("eat")) # "aet" a string, usable as a keyWorth Knowing
Two refinements you’ll see in other people’s solutions.
collections.defaultdict removes the existence check:
from collections import defaultdict
def group_anagrams(strs):
groups = defaultdict(list)
for word in strs:
groups["".join(sorted(word))].append(word)
return list(groups.values())A defaultdict(list) creates an empty list automatically the first time a key is touched, so the if key not in groups block disappears. Cleaner, though I'd write the explicit version in an interview unless asked, since it makes the logic visible.
You can also drop the sort entirely by using letter counts as the key:
key = tuple(sorted(Counter(word).items()))or, for lowercase-only input, a 26-length tuple of counts. That brings the per-word cost from k log k down to k, giving O(n · k) overall. It's the theoretically better answer, but sorting is easier to write correctly under pressure and k is usually small.

![How Harris Finds Corners [Computer Vision]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*ItXucl5GOsTBAUt-PSl3Gg.jpeg)
![Why Derivative Filters Break on Noisy Images [Computer Vision]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*lFtJlmZU-iHSTX42XSFDWA.jpeg)
![Vectors [ML Math]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*vGvmn2pRRohfpstlxImeog.jpeg)
![Valid Palindrome [Python Algorithm]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*ard8pDZEBsB2ib-uFm8SMg.jpeg)



