Problem 275084 · medium · Phase 02 Linear Data Structures

Anagram Families

strings · anagrams · dicts · sorting

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

Examples

Input:  words = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output: [["ate", "eat", "tea"], ["nat", "tan"], ["bat"]]

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
Starting Python…