Group Anagrams
Problem Statement
You’re a word organizer with a list of strings. Your task: group all anagrams together. This medium-level hashing challenge is a linguistic sorting spree—use a map to cluster those scrambled siblings!
Example
Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
Input: strs = [""]
Output: [[""]]
Input: strs = ["a"]
Output: [["a"]]
Code
Java
Python
JavaScript
public class Solution {
public List> groupAnagrams(String[] strs) {
Map> map = new HashMap<>();
for (String str : strs) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
map.computeIfAbsent(key, k -> new ArrayList<>()).add(str);
}
return new ArrayList<>(map.values());
}
}
from collections import defaultdict
def group_anagrams(strs):
anagrams = defaultdict(list)
for s in strs:
key = ''.join(sorted(s))
anagrams[key].append(s)
return list(anagrams.values())
function groupAnagrams(strs) {
let map = new Map();
for (let str of strs) {
let key = str.split('').sort().join('');
if (!map.has(key)) map.set(key, []);
map.get(key).push(str);
}
return Array.from(map.values());
}
Explanation
- Hashing Insight: Sorted string as key groups anagrams together.
- Flow: Sort each string’s chars to create a unique key, map it to a list of originals.
- Example Walkthrough: "eat" → "aet", maps to ["eat", "tea", "ate"].
- Python Tip: defaultdict simplifies initialization.
- Alternative: Use char count arrays as keys for O(nk) without sorting.
Note
Time complexity: O(nk log k), Space complexity: O(nk) where k is max string length. A hashing symphony for word lovers!
