You get a list of words. Group the anagrams together: two words are anagrams when they are made of the same letters, the same number of times each, like listen and silent. Return the groups, in any order.
Example: for ["ear", "arc", "rare", "are", "car"], the answer is [["ear", "are"], ["arc", "car"], ["rare"]]. rare has the letters of ear, but one r more, so it is alone.
Try it yourself first: LeetCode 49 ↗. Then step through the solution below.
Take the words one by one and test each against the first word of every group so far, by counting the letters of both; join the first group that matches, or start a new one. With n words of up to k letters and as many groups as words, that is O(n2 · k) time.
The clue is in the words "made of the same letters". Sort the letters of a word, and every one of its anagrams sorts to the same string: ear, are and era all give aer. Words that are not anagrams never do.
So the sorted letters are a key, and a hash map from each key to its list of words does the grouping in one pass: each word finds its group with one lookup, however many groups there are, with no comparison against the other groups.
The player runs the code on the example. Press → for each step: the lines it runs light up in the code.
On a phone, Full screen keeps the picture and the code on one screen.
from collections import defaultdict def group_anagrams(words): groups = defaultdict(list) for word in words: key = ''.join(sorted(word)) groups[key].append(word) return list(groups.values())
Now write it yourself on LeetCode 49 ↗, or go on: Valid Parentheses →
groups starts empty. It will map each key, the letters of a word sorted, to the words that have it.word takes the first word, ear.key. They are not in order yet.key of ear is aer.groups: aer is not there yet, so it gets an empty list.key.groups: acr is not there yet, so it gets an empty list.key.groups: aerr is not there yet, so it gets an empty list.key.groups: it is there already, with ear.key.groups: it is there already, with arc.groups: [ear, are], [arc, car] and [rare].Note
In Python, sorted gives a list, and a list cannot be a dictionary key, so the code joins the letters back into a string. In Java, sorting gives a char[], and a map compares arrays by where they are in memory, so every word would get a group of its own: make a String from it.
| Approach | Time | Space |
|---|---|---|
| Brute force: test each word against every group | O(n2 · k) | O(n · k) |
| Sorted letters as the key of a hash map this page | O(n · k log k) | O(n · k) |
| Letter counts as the key | O(n · k) | O(n · k) |
n is the number of words, and k the length of the longest one.
[""]: its key is the empty string, and it is a group of its own: [[""]].["tea", "tea"]: both get the key aet and share a group: [["tea", "tea"]].["ab", "cd"]: every key is new, and each word is a group of one.The blocks below are steps of Group Anagrams in words, and two of them do not belong. Put the right ones in order and check: your algorithm runs on the example, ["ear", "arc", "rare", "are", "car"], so a mistake shows in its answer. Once it is right, the code appears beside your blocks.
Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. Two of them don't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.
Your algorithm
Blocks
Now write it yourself on LeetCode 49 ↗, or go on: Valid Parentheses →
from collections import defaultdict def group_anagrams(words): groups = defaultdict(list) for word in words: key = ''.join(sorted(word)) groups[key].append(word) return list(groups.values())Can the key cost less than sorting? Yes: count the letters. With only the 26 lowercase letters, a key of 26 counts is built in O(k), so the whole is O(n · k). Keep the counts apart, as a tuple or with a separator such as 1#0#2#…: run together, the counts 1 and 11 read the same as 11 and 1.
LeetCode is a trademark of LeetCode LLC. VisiGrab is not affiliated with LeetCode or with Blind; the problems are told in our own words, with our own examples.