💡
Exercise 27

Group Anagrams 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

LeetCode #49: Group Anagrams — combines hash maps with string manipulation. A great Medium problem.

Given a list of strings, group the anagrams together. Two strings are anagrams if they have the same characters.

Example:
["eat","tea","tan","ate","nat","bat"]
[["eat","tea","ate"], ["tan","nat"], ["bat"]]

Key Insight: Anagrams have the same sorted character sequence. sorted('eat') = ['a','e','t'] and sorted('tea') = ['a','e','t']. Use sorted string as hash map key!

💭 Now it's your turn! Using the approach above, implement your solution in the editor. You've got this! 💪

Complexity: Time O(n · k log k) where k is max string length, Space O(n·k)

📋 Instructions
Implement `groupAnagrams(strs)` using a hash map with sorted character tuples as keys. Return a list of groups. Order within groups and order of groups doesn't matter — just group correctly.
groups = defaultdict(list). For each s in strs: key = tuple(sorted(s)), then groups[key].append(s). Return list(groups.values()). The tuple(sorted(s)) creates a hashable key that's the same for all anagrams.
⚠️ Try solving it yourself first — you'll learn more!
from collections import defaultdict

def groupAnagrams(strs):
    groups = defaultdict(list)
    for s in strs:
        key = tuple(sorted(s))   # Sorted chars as key
        groups[key].append(s)
    return list(groups.values())
🧪 Test Cases
Input
Run your code
Expected
['ate', 'eat', 'tea'] ['bat'] ['nat', 'tan']
Expected program output
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.