Back to Practice
#0310

Group Anagrams

MediumPython24 min20 XP

Problem

Given a list of lowercase words, return groups of anagrams. Sort words inside each group, then sort the list of groups by the first word in each group for stable output.

Why This Matters

Group Anagrams is the practical upgrade from checking two anagrams to organizing an entire list by a canonical key.

Function Signature

def group_anagrams(words):

Examples

Example 1
Inputwords = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output[["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]

eat, tea, and ate share the same sorted-letter key; tan and nat share another key.

Constraints

  • Return the exact requested value.
  • Handle edge cases cleanly.
  • Prefer clear Python code before clever one-liners.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Classic groups
Input["eat", "tea", "tan", "ate", "nat", "bat"]
Expected[["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]

Words with the same letter counts are grouped together.

Empty string group
Input["", "b", ""]
Expected[["", ""], ["b"]]

Empty strings are anagrams of each other.

Hidden Test Categories
all words uniqueall words same grouprepeated identical words