Intuition
Anagrams are permutations of the same letters — sort their characters and they collide to the same canonical string. Group by that key.
Explanation
Approach
- Build a dict
groups: sorted_key -> list[str]. - For each
s, computekey = "".join(sorted(s))and append. - Return
list(groups.values()).
Implementation
import java.util.*;
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> groups = new HashMap<>();
for (String s : strs) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
groups.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}
return new ArrayList<>(groups.values());
}
}