"""Week 3: Searching. Binary search templates that never go off by one."""
from __future__ import annotations

from typing import Callable, List


def binary_search(items: List[int], target: int) -> int:
    """Closed interval [lo, hi]. Returns an index of target or -1."""
    lo, hi = 0, len(items) - 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2
        if items[mid] == target:
            return mid
        if items[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1


def lower_bound(items: List[int], target: int) -> int:
    """First index with items[i] >= target (len(items) if none). Half-open [lo, hi)."""
    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: List[int], target: int) -> int:
    """First index with items[i] > target."""
    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 count_occurrences(items: List[int], target: int) -> int:
    return upper_bound(items, target) - lower_bound(items, target)


def first_true(lo: int, hi: int, predicate: Callable[[int], bool]) -> int:
    """Binary search on the answer: smallest x in [lo, hi] with predicate(x) true,
    assuming predicate is False...False True...True. Returns hi + 1 if never true."""
    answer = hi + 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if predicate(mid):
            answer, hi = mid, mid - 1
        else:
            lo = mid + 1
    return answer


def integer_sqrt(n: int) -> int:
    """floor(sqrt(n)) using first_true on 'x * x > n'."""
    if n < 0:
        raise ValueError("n must be non-negative")
    return first_true(0, n + 1, lambda x: x * x > n) - 1


def search_rotated(items: List[int], target: int) -> int:
    lo, hi = 0, len(items) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if items[mid] == target:
            return mid
        if items[lo] <= items[mid]:
            if items[lo] <= target < items[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        elif items[mid] < target <= items[hi]:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1


def search_sorted_matrix(matrix: List[List[int]], target: int) -> bool:
    """Rows and columns sorted: start top-right, step left or down. O(rows + cols)."""
    if not matrix or not matrix[0]:
        return False
    r, c = 0, len(matrix[0]) - 1
    while r < len(matrix) and c >= 0:
        if matrix[r][c] == target:
            return True
        if matrix[r][c] > target:
            c -= 1
        else:
            r += 1
    return False
