Group Anagrams

Words that are permutations of one another belong to the same anagram class. For two strings, membership in one class means their letters can be rearranged into a common arrangement, which holds exactly when every letter occurs with the same multiplicity in both. The task is to partition an input list of strings into these classes and return the classes in any order, with the words inside each class in any order as well.

The input contains lowercase English letters, and the empty string is a legal word. Two empty strings are anagrams of each other. Capital letters, digits and punctuation do not occur, so a 26-slot frequency vector fully describes the content of a word.

The natural approach attaches a canonical key to every word and groups by that key. Sorting the characters of a word produces a key that ignores order, at the cost of O(k log k) per word for length k. Counting characters produces a key in O(k) and is usually faster when words are long: build a 26-entry count, then serialize it, for instance as the counts joined by a separator. A hash map from key to the list of words seen with that key finishes the grouping. Total work is O(total characters) with the counting key, and memory is proportional to the input size.

Examples
Input: ["eat","tea","tan","ate","nat","bat"]
Output: [["eat","tea","ate"],["tan","nat"],["bat"]]
Hints
Related Problems

Group Anagrams

Words that are permutations of one another belong to the same anagram class. For two strings, membership in one class means their letters can be rearranged into a common arrangement, which holds exactly when every letter occurs with the same multiplicity in both. The task is to partition an input list of strings into these classes and return the classes in any order, with the words inside each class in any order as well.