26. Group Anagrams

Medium · String

Group anagrams together from a list of strings. Two strings are anagrams if they contain exactly the same characters in any order. Return a list of groups where each group contains all anagrams of each other. Within each group, sort the strings in ascending alphabetical order. Then sort the outer list lexicographically by JSON.stringify (so groups are ordered by their stringified representation). For example, with ["eat","tea","tan","ate","nat","bat"], the anagrams "eat", "tea", and "ate" form one group, "tan" and "nat" form another, and "bat" stands alone.

Examples

Example 1
Input: ["eat","tea","tan","ate","nat","bat"]
Output: [["ate","eat","tea"],["bat"],["nat","tan"]]
Explanation: Three anagram groups, canonical ordering
Example 2
Input: [""]
Output: [[""]]
Explanation: Single empty-string group

Constraints