"""Counting sort (for integers).

Idea
----
Instead of comparing values, count how many times each value appears, then
turn the counts into prefix sums so ``count[v]`` tells you where the last
copy of ``v`` belongs. Walking the input backwards keeps the sort stable,
which is what radix sort relies on.

Complexity
----------
Time:  O(n + k), where k = max - min + 1 is the value range
Space: O(n + k). Stable.

When to use
-----------
Integers (or keys mappable to integers) with a small range compared with n,
such as ages, grades or bytes. Useless when k is huge.
"""

from collections.abc import Callable, Sequence
from typing import TypeVar

T = TypeVar("T")


def counting_sort(items: Sequence[T], key: Callable[[T], int] | None = None) -> list[T]:
    """Return a new list sorted by the integer ``key`` (identity by default)."""
    if not items:
        return []
    get = key if key is not None else (lambda x: x)  # type: ignore[assignment,return-value]
    keys = [get(x) for x in items]
    lo, hi = min(keys), max(keys)
    counts = [0] * (hi - lo + 1)
    for k in keys:
        counts[k - lo] += 1
    for i in range(1, len(counts)):
        counts[i] += counts[i - 1]
    output: list[T] = [None] * len(items)  # type: ignore[list-item]
    for item, k in zip(reversed(items), reversed(keys)):
        counts[k - lo] -= 1
        output[counts[k - lo]] = item
    return output
