Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Group Anagrams

Hard · 75 XP

Group words that are anagrams of each other. Print one line per group: the sorted words joined by spaces, groups ordered by first appearance.

Target output
ate eat tea
nat tan
bat
Blank · autosaved
PYgroup-anagrams.py
Run your code to check it…
Guide

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

  1. "eat" → "aet" starts a group. "tea" → "aet" joins it. "tan" → "ant" starts a second group.
  2. "ate" → "aet" joins the first, "nat" → "ant" joins the second, and "bat" → "abt" starts a third.
  3. 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.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path