"""Radix sort (least significant digit first, base 10).

Idea
----
Sort non-negative integers one digit at a time, starting with the ones
digit, using a *stable* sort for each pass. Because every pass is stable,
the order established by lower digits survives when higher digits tie.

Complexity
----------
Time:  O(d * (n + b)), where d is the number of digits and b the base (10)
Space: O(n + b)

When to use
-----------
Large arrays of fixed-width integer keys (IDs, IP addresses, dates as
integers). Negative numbers need an offset or a separate pass.
"""

from collections.abc import Sequence


def radix_sort(numbers: Sequence[int], base: int = 10) -> list[int]:
    """Return a new list with the non-negative integers sorted ascending."""
    if any(n < 0 for n in numbers):
        raise ValueError("radix_sort only supports non-negative integers")
    result = list(numbers)
    if not result:
        return result
    place = 1
    largest = max(result)
    while largest // place > 0:
        buckets: list[list[int]] = [[] for _ in range(base)]
        for n in result:
            buckets[(n // place) % base].append(n)
        result = [n for bucket in buckets for n in bucket]
        place *= base
    return result
