easy +10 pts

Anagram Groups by Size

Group strings by anagram identity and return groups sorted by size then lexicographically.

Write a function `anagram_groups_by_size(words)` that takes a list of strings `words` (all lowercase letters, no spaces) and returns a list of groups. Each group is a list of words that are anagrams of each other (same letters, same frequency, ignoring order). The groups should be sorted in ascending order of group size (i.e., number of words in the group). If two groups have the same size, sort them lexicographically by the first word in the group (using Python string comparison). Within each group, the words should be sorted lexicographically. The function must return a list of lists, where each inner list contains the sorted words of one group. Words with no anagram partners form a group of size 1. Example: - `anagram_groups_by_size(["eat", "tea", "tan", "ate", "nat", "bat"])` returns `[["bat"], ["nat", "tan"], ["ate", "eat", "tea"]]`. Ensure your solution handles an empty input list. Constraints: - 0 <= len(words) <= 1000 - Each word length is between 1 and 20. - Words consist of lowercase English letters only.

Constraints

0 <= len(words) <= 1000 Each word length: 1 to 20 Lowercase letters only Time: O(N * K log K) or better, where N = len(words), K = max word length.

Example

>>> anagram_groups_by_size(["eat", "tea", "tan", "ate", "nat", "bat"])
[["bat"], ["nat", "tan"], ["ate", "eat", "tea"]]
>>> anagram_groups_by_size(["hello", "world"])
[["hello"], ["world"]]
>>> anagram_groups_by_size(["a", "b", "a"])
[["b"], ["a", "a"]]
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a dictionary mapping a canonical form (e.g., sorted string) to a list of words.
After grouping, sort each group's words, then sort the groups by length, then by the first word.
Remember to handle an empty input list with an empty list result.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.