#49

Group Anagrams

Medium Canonical key + HashMap

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Group the strings so that anagrams end up in the same group.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: put anagrams in the same group.

Why this works: anagrams share the same sorted spelling; use it as a HashMap key.

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

"aet" → eat, tea, ate"ant" → tan, nat"abt" → bat

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using the char[] itself as a map key — arrays use identity equality. Convert to a String.

Solve on LeetCode ↗
Complexity
  • Time: O(n · k log k), k = max word length (O(n·k) with a count key).
  • Space: O(n · k).
Topic: Strings
🎬 Episodes 16–20: video coming soon