"""Quickselect: the k-th smallest element without fully sorting.

Idea
----
Use quick sort's partition step, but only recurse into the side that holds
position ``k``. On average the work halves each round: n + n/2 + n/4 + ...
which sums to about 2n.

Complexity
----------
Time:  O(n) expected, O(n^2) worst case (made unlikely by a random pivot)
Space: O(n) for this copy-based version; an in-place variant uses O(1)

When to use
-----------
Medians, percentiles and "k-th largest" questions where you need one order
statistic, not a fully sorted list.
"""

import random
from collections.abc import Sequence
from typing import Any


def quickselect(items: Sequence[Any], k: int) -> Any:
    """Return the k-th smallest value (0-based) of ``items``."""
    if not 0 <= k < len(items):
        raise IndexError("k out of range")
    values = list(items)
    while True:
        pivot = random.choice(values)
        lows = [v for v in values if v < pivot]
        pivots = [v for v in values if v == pivot]
        if k < len(lows):
            values = lows
        elif k < len(lows) + len(pivots):
            return pivot
        else:
            k -= len(lows) + len(pivots)
            values = [v for v in values if v > pivot]
