← Back to DSA Animator
Group Anagrams LC #49 Medium HashMap · Sorted Key
Problem

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

Example 1
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Constraints: 1 ≤ strs.length ≤ 10⁴ | 0 ≤ strs[i].length ≤ 100 | lowercase English letters
Try Examples
Custom:
Approach
Sort each word's characters → use sorted string as HashMap key
All anagrams share the same sorted form (e.g. "eat" → "aet"). Bucket words by key in one pass. O(n · k log k) time.
Word List
Sorted Key Transformation
word
sorted key
Group Buckets (map)
Variables
i
word
key
groups
0
size
0
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Create empty Map<String, List<String>>
2
For each word: sort its characters → canonical key
3
map.computeIfAbsent(key).add(word) — bucket by key
4
Return new ArrayList(map.values())
Time
O(n·k log k)
Space
O(n·k)
Why This Works

Sorting a word gives its canonical form — all anagrams produce the identical sorted string. Using that as a HashMap key buckets every anagram together in a single pass, without comparing every pair of words.