def lower_bound(values: list[int], target: int) -> int:
    """Find the first position whose value is at least target.

    Args:
        values: Integers in nondecreasing order.
        target: Value that defines the lower bound.

    Returns:
        The first qualifying index, or len(values) if no value qualifies.
    """
    low, high = 0, len(values)
    while low < high:
        middle = (low + high) // 2
        if values[middle] < target:
            low = middle + 1
        else:
            high = middle
    return low


values = [2, 5, 5, 9, 13]
target = 5
low, high = 0, len(values)
while low < high:
    middle = (low + high) // 2
    print("Bounds", (low, high), "middle", middle, "value", values[middle])
    if values[middle] < target:
        low = middle + 1
    else:
        high = middle
print("First qualifying index:", lower_bound(values, target))
print("Insertion after all values:", lower_bound(values, 20))

def interval_start(interval: tuple[int, int]) -> int:
    """Return the start coordinate used as a sorting key.

    Args:
        interval: Start and end coordinates of an interval.

    Returns:
        The start coordinate.
    """
    return interval[0]


def merge_closed_intervals(
    intervals: list[tuple[int, int]],
) -> list[tuple[int, int]]:
    """Return the union of closed intervals without changing the input.

    Args:
        intervals: Integer endpoint pairs with start no greater than end.

    Returns:
        Sorted closed intervals with no overlap or shared endpoint.

    Raises:
        ValueError: If an interval starts after it ends.
    """
    for start, end in intervals:
        if start > end:
            raise ValueError("an interval must start at or before its end")
    ordered = sorted(intervals, key=interval_start)
    merged: list[tuple[int, int]] = []
    for start, end in ordered:
        if not merged or start > merged[-1][1]:
            merged.append((start, end))
        else:
            previous_start, previous_end = merged[-1]
            merged[-1] = (previous_start, max(previous_end, end))
    return merged


intervals = [(6, 8), (1, 3), (3, 5), (10, 12)]
ordered = sorted(intervals, key=interval_start)
print("Sorted intervals:", ordered)
for count in range(1, len(ordered) + 1):
    print("Processed", ordered[:count],
          "union", merge_closed_intervals(ordered[:count]))
print("Final union:", merge_closed_intervals(intervals))
print("Original input:", intervals)

assert lower_bound([], 4) == 0
assert lower_bound([5, 5, 5], 5) == 0
assert lower_bound([2, 5], 1) == 0
assert lower_bound([2, 5], 4) == 1
assert lower_bound([2, 5], 6) == 2
assert merge_closed_intervals([]) == []
assert merge_closed_intervals([(1, 9), (2, 3)]) == [(1, 9)]
assert merge_closed_intervals([(2, 2), (2, 4)]) == [(2, 4)]
assert merge_closed_intervals([(1, 3), (4, 6)]) == [(1, 3), (4, 6)]
print("The search and interval boundary cases pass.")

def fits_capacity(
    sizes: list[int], max_batches: int, capacity: int
) -> bool:
    """Check whether ordered positive sizes fit within a batch limit.

    Args:
        sizes: Positive integer sizes in fixed order.
        max_batches: Positive maximum number of nonempty batches.
        capacity: Nonnegative maximum total allowed in one batch.

    Returns:
        Whether every size fits without exceeding either limit.
    """
    if not sizes:
        return True
    batches = 1
    current = 0
    for size in sizes:
        if size > capacity:
            return False
        if current + size > capacity:
            batches += 1
            current = size
            if batches > max_batches:
                return False
        else:
            current += size
    return True


def minimum_batch_capacity(sizes: list[int], max_batches: int) -> int:
    """Find the smallest feasible capacity for ordered record batches.

    Args:
        sizes: Positive integer record sizes. The input remains unchanged.
        max_batches: Positive maximum number of contiguous batches.

    Returns:
        The minimum capacity, or zero when sizes is empty.

    Raises:
        ValueError: If max_batches is nonpositive or a size is nonpositive.
    """
    if max_batches <= 0 or any(size <= 0 for size in sizes):
        raise ValueError("batch limit and record sizes must be positive")
    if not sizes:
        return 0
    low, high = max(sizes), sum(sizes)
    while low < high:
        middle = (low + high) // 2
        if fits_capacity(sizes, max_batches, middle):
            high = middle
        else:
            low = middle + 1
    return low


record_sizes = [7, 2, 5, 10, 8]
batch_limit = 2
low, high = max(record_sizes), sum(record_sizes)
while low < high:
    middle = (low + high) // 2
    feasible = fits_capacity(record_sizes, batch_limit, middle)
    print("Bounds:", (low, high), "Capacity:", middle, "Fits:", feasible)
    if feasible:
        high = middle
    else:
        low = middle + 1
answer_capacity = minimum_batch_capacity(record_sizes, batch_limit)
print("Minimum capacity:", answer_capacity)
print("One lower capacity fits:", fits_capacity(
    record_sizes, batch_limit, answer_capacity - 1
))

assert minimum_batch_capacity([], 1) == 0
assert minimum_batch_capacity([6], 4) == 6
assert minimum_batch_capacity([2, 3, 4], 1) == 9
assert minimum_batch_capacity([2, 3, 4], 3) == 4
assert minimum_batch_capacity(record_sizes, batch_limit) == 18
assert record_sizes == [7, 2, 5, 10, 8]
print("Empty, single-record, batch-limit, and input-preservation checks pass.")
