Skip to content
BytePatterns

Group Anagrams Together

MediumStrings#hash-map#canonical-form~20m

Problem

Group a list of words so that words using exactly the same letters, in any order, land in the same group. Return the groups with each group's words sorted, and the groups themselves sorted.

Examples

Input:  words = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output: [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]
Why:    eat, tea and ate all use a, e and t
Input:  words = ["ab", "ba", "abc"]
Output: [["ab", "ba"], ["abc"]]
Why:    length alone separates the second group
Input:  words = [""]
Output: [[""]]
Why:    edge case, the empty word forms its own group

Hints

0 / 3

Stuck on the idea rather than the code? Group Anagrams covers it.