Neural Mastery
← Practice
Group Anagramsmedium

Group Anagrams

medium Coding Interview Patterns 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Two Pointers & Sliding Window, Step by Step
Pattern
1
L
2
3
4
6
R
arr[L]=1 + arr[R]=6 = 7 vs target 6 -> too big, move R left
Step 1 / 3
Both modes run the exact algorithm described on the linked practice problem, one real step at a time -- not a pre-rendered animation. Edit the input and every step recomputes live.

Implement Group Anagrams -- using a canonical key (each word's own sorted letters) as a hash-map key is the general pattern for "bucket items by some derived signature," not just for anagrams.

Related Skills

Task

Implement group_anagrams(words): for each word, compute its sorted-letters key (e.g. "eat" -> "aet") and append it to that key's bucket in a dict. Return the buckets as a list of lists, sorted by key alphabetically.

Function Signature

group_anagrams(words: list[str]) -> list[list[str]]

Examples

Example 1: Three Groups
Input: words = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
Output: [['bat'], ['eat', 'tea', 'ate'], ['tan', 'nat']]
Explanation: Sorted-key order: "abt" < "aet" < "ant"
Example 2: Single Empty String
Input: words = ['']
Output: [['']]

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Two words are anagrams exactly when their sorted-letters keys are identical.
  • Within a group, preserve the words' original relative order from the input.
  • Return the groups themselves sorted by their key string in ascending alphabetical order, so the output is fully deterministic.
Python3Saved ✓
def group_anagrams(words: list[str]) -> list[list[str]]:
"""Group words that are anagrams of each other. Return the groups
sorted by their sorted-letters key in ascending alphabetical order;
within each group, preserve the words' original relative order."""
# Your implementation here
pass

Case 1: Three Groups
Input: words = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
Expected: [['bat'], ['eat', 'tea', 'ate'], ['tan', 'nat']]
Case 2: Single Empty String
Input: words = ['']
Expected: [['']]