Given an array of strings strs, group the anagrams together. You can return the answer in any order.
strs = ["eat","tea","tan","ate","nat","bat"][["bat"],["nat","tan"],["ate","eat","tea"]]Map<String, List<String>>keymap.computeIfAbsent(key).add(word) — bucket by keynew ArrayList(map.values())Sorting a word gives its canonical form — all anagrams produce the identical sorted string. Using that as a HashMap key buckets every anagram together in a single pass, without comparing every pair of words.
Comparing every word with every other word is O(n²). For thousands of words, that is far too slow.
Sort the letters of an anagram, and they all become the same string. eat, tea and ate all sort to a e t. So use the sorted word as the hash map key. Every word goes into the list for its key.
Anagrams share one canonical key, their sorted letters. Group by that key in a hash map.
Run the animation above on your own input, or watch the 1:21 video explanation of Group Anagrams with a dry run and Java code.