"""Binary search, plus lower/upper bound.

Idea
----
On a sorted sequence, compare the target with the middle element and throw
away the half that cannot contain it. Each step halves the search space.

The most reusable form is ``lower_bound``: the first index whose value is
>= target. It never "misses" and gives you the insertion point for free.
``upper_bound`` is the first index whose value is > target, so the number of
copies of ``x`` is ``upper_bound(x) - lower_bound(x)``. These match the
behaviour of ``bisect.bisect_left`` and ``bisect.bisect_right``.

Complexity
----------
Time:  O(log n)
Space: O(1) (iterative)

Pitfalls
--------
Use a half-open range ``[lo, hi)`` and ``while lo < hi``; mixing closed and
half-open conventions is the classic source of infinite loops and
off-by-one errors.
"""

from collections.abc import Sequence
from typing import Any


def lower_bound(items: Sequence[Any], target: Any) -> int:
    """First index ``i`` with ``items[i] >= target`` (len(items) if none)."""
    lo, hi = 0, len(items)
    while lo < hi:
        mid = (lo + hi) // 2
        if items[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo


def upper_bound(items: Sequence[Any], target: Any) -> int:
    """First index ``i`` with ``items[i] > target`` (len(items) if none)."""
    lo, hi = 0, len(items)
    while lo < hi:
        mid = (lo + hi) // 2
        if items[mid] <= target:
            lo = mid + 1
        else:
            hi = mid
    return lo


def binary_search(items: Sequence[Any], target: Any) -> int:
    """Return an index of ``target`` in sorted ``items`` or -1."""
    i = lower_bound(items, target)
    return i if i < len(items) and items[i] == target else -1
