DSA AnimatorDSA animations
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.

How to solve Group Anagrams

LeetCode 49 · Medium · Strings · Pattern: Hash Map

Why the obvious approach is slow

Comparing every word with every other word is O(n²). For thousands of words, that is far too slow.

The key idea

Sort the letters of an anagram, and they all become the same string. eat, tea and ate all sort to a e t. So use the sorted word as the hash map key. Every word goes into the list for its key.

Remember

Anagrams share one canonical key, their sorted letters. Group by that key in a hash map.

Run the animation above on your own input, or watch the 1:21 video explanation of Group Anagrams with a dry run and Java code.

More Strings problems