← Back to libraryQuestion 99 of 273
⌨️Java CodingAdvanced

Group Anagrams Together

📌 Definition:

Group words that are anagrams of each other (e.g. ["eat","tea","tan","ate","nat","bat"] -> [["eat","tea","ate"],["tan","nat"],["bat"]]).

📖 Detailed Explanation:

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).

💻 Solutions:
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())
🔑 Key Points:
  • Sorted characters is a canonical anagram key
  • Group words into buckets by that key
  • Count-based key avoids the per-word sort
  • O(n * k log k)
🌍 Real-World Example:

Grouping by a canonical key is a universal pattern — deduplicating records by a normalized signature, clustering equivalent inputs.

🎯 Scenario-Based Interview Question:

Two words are anagrams but land in different groups. What is likely wrong with the key?