"""Stage 6: Binary Search (problems 44-53)."""
from __future__ import annotations

import bisect
from collections import defaultdict
from typing import List


def search(nums: List[int], target: int) -> int:
    """LC 704. Closed interval [lo, hi]; loop while lo <= hi."""
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1


def search_matrix(matrix: List[List[int]], target: int) -> bool:
    """LC 74. Treat the matrix as one sorted array of length rows*cols."""
    rows, cols = len(matrix), len(matrix[0])
    lo, hi = 0, rows * cols - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        value = matrix[mid // cols][mid % cols]
        if value == target:
            return True
        if value < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return False


def min_eating_speed(piles: List[int], h: int) -> int:
    """LC 875. Binary search on the answer: smallest speed k whose total hours <= h."""
    lo, hi = 1, max(piles)
    while lo < hi:
        k = (lo + hi) // 2
        hours = sum((p + k - 1) // k for p in piles)
        if hours <= h:
            hi = k
        else:
            lo = k + 1
    return lo


def find_min(nums: List[int]) -> int:
    """LC 153. Compare mid with the right end to know which half holds the rotation point."""
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] > nums[hi]:
            lo = mid + 1
        else:
            hi = mid
    return nums[lo]


def search_rotated(nums: List[int], target: int) -> int:
    """LC 33. One half around mid is always sorted; check whether target lies inside it."""
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[lo] <= nums[mid]:
            if nums[lo] <= target < nums[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:
            if nums[mid] < target <= nums[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1


class TimeMap:
    """LC 981. Timestamps arrive increasing, so each key's list is sorted; bisect for the floor."""

    def __init__(self) -> None:
        self.times = defaultdict(list)
        self.values = defaultdict(list)

    def set(self, key: str, value: str, timestamp: int) -> None:
        self.times[key].append(timestamp)
        self.values[key].append(value)

    def get(self, key: str, timestamp: int) -> str:
        i = bisect.bisect_right(self.times[key], timestamp)
        return self.values[key][i - 1] if i else ""


def find_median_sorted_arrays(nums1: List[int], nums2: List[int]) -> float:
    """LC 4. Binary search a partition of the shorter array so left halves hold half the items."""
    a, b = (nums1, nums2) if len(nums1) <= len(nums2) else (nums2, nums1)
    total = len(a) + len(b)
    half = (total + 1) // 2
    lo, hi = 0, len(a)
    while lo <= hi:
        i = (lo + hi) // 2
        j = half - i
        a_left = a[i - 1] if i > 0 else float("-inf")
        a_right = a[i] if i < len(a) else float("inf")
        b_left = b[j - 1] if j > 0 else float("-inf")
        b_right = b[j] if j < len(b) else float("inf")
        if a_left <= b_right and b_left <= a_right:
            if total % 2:
                return float(max(a_left, b_left))
            return (max(a_left, b_left) + min(a_right, b_right)) / 2
        if a_left > b_right:
            hi = i - 1
        else:
            lo = i + 1
    raise ValueError("inputs must be sorted")


def search_range(nums: List[int], target: int) -> List[int]:
    """LC 34. Two lower-bound searches: for target and for target + 1."""
    left = bisect.bisect_left(nums, target)
    if left == len(nums) or nums[left] != target:
        return [-1, -1]
    return [left, bisect.bisect_left(nums, target + 1) - 1]


def find_peak_element(nums: List[int]) -> int:
    """LC 162. If nums[mid] < nums[mid+1], a peak exists to the right (walk uphill)."""
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] < nums[mid + 1]:
            lo = mid + 1
        else:
            hi = mid
    return lo


def ship_within_days(weights: List[int], days: int) -> int:
    """LC 1011. Answer lies in [max(weights), sum(weights)]; greedy day count is monotonic."""

    def days_needed(capacity: int) -> int:
        used, load = 1, 0
        for w in weights:
            if load + w > capacity:
                used += 1
                load = 0
            load += w
        return used

    lo, hi = max(weights), sum(weights)
    while lo < hi:
        mid = (lo + hi) // 2
        if days_needed(mid) <= days:
            hi = mid
        else:
            lo = mid + 1
    return lo
