You get a list of words. Group the words that are anagrams of each other. Anagrams use the same letters in a different order.
DSA Animator › DSA Revision › Strings › Group Anagrams
Remember: anagrams share one canonical key, their sorted letters. Group by that key in a hash map. The video solves Group Anagrams (LeetCode 49, Medium) with the Hash Map pattern from the Strings topic, and you can replay every step in the interactive Group Anagrams animation.
You get a list of words. Group the words that are anagrams of each other. Anagrams use the same letters in a different order.
eat, tea, tan, ate, nat and bat. eat, tea and ate form one group. tan and nat form a second group. And bat stands alone.
Comparing every word with every other word is O of n squared. 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.
eat has the key a e t, so a new list starts. tea also has the key a e t, so it joins that list. tan has the key a n t, a new list. ate has the key a e t, so it joins the first list. nat has the key a n t, so it joins the second list. bat has the key a b t, a third list. The three lists in the map are the answer.
In code, create a map from a string key to a list of words. For each word, sort its letters to build the key. computeIfAbsent gets or creates the list, and the word is added to it. Finally, return the map values. Time is O of n times k log k, where k is the word length.
Remember: anagrams share one canonical key, their sorted letters. Group by that key in a hash map.