Group Anagrams
Hard · 75 XPGroup words that are anagrams of each other. Print one line per group: the sorted words joined by spaces, groups ordered by first appearance.
ate eat tea nat tan bat
The sorted letters of a word make a key every anagram shares: "".join(sorted(word)).
words = ["eat", "tea", "tan", "ate", "nat", "bat"]
groups = {}
for word in words:
groups.setdefault("".join(sorted(word)), []).append(word)
for key, group in groups.items():
print(" ".join(sorted(group)))
Run your code to check it…
How to approach Group Anagrams
Anagrams contain the same letters in a different order, so sorting the letters gives every anagram the same signature: "eat", "tea" and "ate" all sort to "aet". That signature becomes a dictionary key, and each key collects its group.
groups.setdefault(key, []).append(word) creates the list the first time a key appears and appends to it afterwards. Dictionaries keep insertion order, so iterating over groups gives the groups in order of first appearance, which the prompt asks for. Sort the words inside each group before printing them.
Worked through on this data
- "eat" → "aet" starts a group. "tea" → "aet" joins it. "tan" → "ant" starts a second group.
- "ate" → "aet" joins the first, "nat" → "ant" joins the second, and "bat" → "abt" starts a third.
- Printed in order, each group sorted: "ate eat tea", "nat tan", "bat".
Common mistakes
- Using
set(word)as the key loses letter counts, so "aab" and "abb" land in the same group. - Using the sorted list itself as the key: lists cannot be dictionary keys. Join it into a string or convert it to a tuple.
- Forgetting to sort within each group prints "eat tea ate" instead of the expected order.
Time and space
Sorting each word of length k costs O(k log k), so n words cost O(n · k log k) time and O(n · k) space. A key of 26 letter counts brings each word down to O(k).
Where this shows up
Grouping by a computed key is the same idea as SQL's GROUP BY and pandas' groupby: deduplicating near-identical records, bucketing log lines by error type, clustering products by normalised name.
Take it further
Build the key from letter counts instead of sorting: a tuple of 26 integers, one per letter of the alphabet.