"""Anagram check and grouping.

Idea
----
Two strings are anagrams when they contain the same characters with the same
counts. Comparing ``Counter`` objects does that in linear time. To *group*
many words, use a canonical key shared by all anagrams: the sorted letters
(O(k log k) per word) or a 26-slot count tuple (O(k) per word, lowercase
a-z only).

Complexity
----------
is_anagram:     O(n) time, O(alphabet) space
group_anagrams: O(total characters * log k) time with sorted keys
"""

from collections import Counter, defaultdict
from collections.abc import Iterable


def is_anagram(a: str, b: str) -> bool:
    """Return True if ``a`` and ``b`` are anagrams (case-sensitive)."""
    return len(a) == len(b) and Counter(a) == Counter(b)


def group_anagrams(words: Iterable[str]) -> list[list[str]]:
    """Group words that are anagrams of each other, keeping input order."""
    groups: dict[str, list[str]] = defaultdict(list)
    for word in words:
        groups["".join(sorted(word))].append(word)
    return list(groups.values())
