Group words that are anagrams of each other (e.g. ["eat","tea","tan","ate","nat","bat"] -> [["eat","tea","ate"],["tan","nat"],["bat"]]).
Anagrams share the same sorted-character signature, so use that sorted string as a hash-map key and append each word to its bucket. O(n * k log k) for n words of length k. A character-count signature avoids the sort for a slightly better O(n * k).
public static List<List<String>> groupAnagrams(String[] words) {
Map<String,List<String>> m = new HashMap<>();
for (String w : words) {
char[] c = w.toCharArray();
java.util.Arrays.sort(c);
m.computeIfAbsent(new String(c), k -> new ArrayList<>()).add(w);
}
return new ArrayList<>(m.values());
}function groupAnagrams(words) {
const m = new Map();
for (const w of words) {
const key = w.split('').sort().join('');
if (!m.has(key)) m.set(key, []);
m.get(key).push(w);
}
return [...m.values()];
}from collections import defaultdict
def group_anagrams(words):
m = defaultdict(list)
for w in words:
m[''.join(sorted(w))].append(w)
return list(m.values())Grouping by a canonical key is a universal pattern — deduplicating records by a normalized signature, clustering equivalent inputs.
Two words are anagrams but land in different groups. What is likely wrong with the key?