Two words are anagrams if one is a rearrangement of the other (case-sensitive, every character counts). Write anagram_families(words) that groups the words into families of mutual anagrams and returns them as a list of lists:
- inside a family, words are sorted alphabetically (duplicates are kept)
- families are ordered by size, largest first; families of equal size are ordered by their first word after this sorting (their alphabetically smallest word), not by where they appear in
words
Examples
Input: words = ["car", "tops", "art", "spot", "arc", "post", "rat"]
Output: [["post", "spot", "tops"], ["arc", "car"], ["art", "rat"]]
Explanation: the two families of size 2 are ordered by "arc" < "art", although "art" appears before "arc" and "car" in the list.
Input: words = []
Output: []
Constraints
0 <= len(words) <= 5000, each word of length at most 20, printable ASCII- Target: O(total characters * log) time
Goals
- Build a canonical key that is identical for all anagrams
- Group values under that key
- Sort groups by a compound key