Group Anagrams - Problem

Imagine you have a collection of words scattered around, and you need to organize them by their anagram groups. Two strings are anagrams if they contain the exact same characters with the same frequency, just rearranged differently.

Given an array of strings strs, your task is to group all anagrams together. Each group should contain strings that are anagrams of each other.

For example: ["eat", "tea", "tan", "ate", "nat", "bat"] should be grouped as [["eat","tea","ate"],["tan","nat"],["bat"]] because:

  • "eat", "tea", "ate" all contain the same characters: e, a, t
  • "tan", "nat" both contain: t, a, n
  • "bat" stands alone with: b, a, t

You can return the groups in any order, and the strings within each group can also be in any order.

Input & Output

example_1.py — Basic Grouping
$ Input: ["eat","tea","tan","ate","nat","bat"]
Output: [["eat","tea","ate"],["tan","nat"],["bat"]]
💡 Note: Strings with the same characters are grouped together: 'eat', 'tea', and 'ate' all contain the same letters (e,a,t). Similarly, 'tan' and 'nat' contain (t,a,n). 'bat' forms its own group.
example_2.py — Single Characters
$ Input: ["a"]
Output: [["a"]]
💡 Note: A single string forms one group by itself.
example_3.py — Empty String
$ Input: [""]
Output: [[""]]
💡 Note: An empty string is its own anagram group.

Visualization

Tap to expand
Anagram Grouping Visualization📚 Library Books (Input Strings):LISTENSILENTSTUDYDUSTY🔑 Alphabetical Signatures (Sorted Keys):EILNSTEILNSTDSTUYDSTUY📖 Organized Shelves (Grouped Results):📚 Anagram Shelf 1Key: EILNSTLISTENSILENT📚 Anagram Shelf 2Key: DSTUYSTUDYDUSTY🎯 Key Insight: Same sorted signature = Anagrams!Hash map groups strings by their alphabetically sorted character signature
Understanding the Visualization
1
Create Signatures
Sort each word's letters alphabetically to create a unique signature
2
Group by Signature
Words with the same signature are anagrams and belong together
3
Collect Results
Return all groups formed by this signature-based organization
Key Takeaway
🎯 Key Insight: Anagrams have identical character signatures when sorted alphabetically. By using sorted strings as hash map keys, we can efficiently group anagrams in O(n×m log m) time!

Time & Space Complexity

Time Complexity
⏱️
O(n×m log m)

n strings, each taking O(m log m) to sort where m is average string length

n
2n
Linearithmic
Space Complexity
O(n×m)

Hash map stores all strings plus sorted keys

n
2n
Linearithmic Space

Constraints

  • 1 ≤ strs.length ≤ 104
  • 0 ≤ strs[i].length ≤ 100
  • strs[i] consists of lowercase English letters only
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28 Apple 22
128.0K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen