Binary search, sorting, and intervals
Order lets you eliminate candidates or combine neighboring records. Binary search uses order to discard half a search range. An interval algorithm first sorts by start position, then compares each interval with the latest merged one. The two patterns share an input property but have different costs.
Find the first value at least as large as a target
Section titled “Find the first value at least as large as a target”Given nondecreasing integers, return the first index whose value is at least the target. Return the list length if every value is smaller. This lower-bound definition handles duplicates and missing targets with the same algorithm.
Maintain a half-open candidate range [low, high). Every index before low
has a value below the target. Every index at or after high has a value at
least as large as the target. At termination, the two boundaries coincide at
the only valid insertion position.
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 = 5low, 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 = middleprint("First qualifying index:", lower_bound(values, target))print("Insertion after all values:", lower_bound(values, 20))Bounds (0, 5) middle 2 value 5Bounds (0, 2) middle 1 value 5Bounds (0, 1) middle 0 value 2First qualifying index: 1Insertion after all values: 5Each iteration removes the middle position or makes it the exclusive boundary.
The range strictly shrinks, so the loop terminates. Time is O(log n) for a
nonempty list and auxiliary space is O(1), under constant-time integer
comparisons. The function assumes sorted input and makes no slices.
Python provides the same lower-bound behavior through bisect_left. Inserting
at its returned position still costs O(n) because a list must shift later
references. A logarithmic search does not make a list insertion logarithmic.
Sort records with a named key
Section titled “Sort records with a named key”The interval problem uses closed intervals [start, end], so both endpoints
belong to the interval. Return their union as disjoint closed intervals in
increasing start order. Intervals that share an endpoint merge. Intervals with
a positive gap remain separate, even if their integer endpoints are adjacent.
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)Sorted intervals: [(1, 3), (3, 5), (6, 8), (10, 12)]Processed [(1, 3)] union [(1, 3)]Processed [(1, 3), (3, 5)] union [(1, 5)]Processed [(1, 3), (3, 5), (6, 8)] union [(1, 5), (6, 8)]Processed [(1, 3), (3, 5), (6, 8), (10, 12)] union [(1, 5), (6, 8), (10, 12)]Final union: [(1, 5), (6, 8), (10, 12)]Original input: [(6, 8), (1, 3), (3, 5), (10, 12)]After each iteration, merged is the union of the processed prefix. Its
intervals are sorted and disjoint. A new start cannot overlap any interval
before the last one without also overlapping the last one. Extending only the
last endpoint therefore preserves the invariant.
The max call matters when an interval lies inside an earlier one. Replacing
the previous endpoint with the new endpoint would incorrectly shorten the
union. The strict start > previous_end comparison implements the stated
closed-interval policy. Half-open intervals need a separate policy about whether
touching intervals should be combined.
For n intervals, the function costs O(n log n) worst-case time for sorting
and O(n) time for the scan. The sorted copy and Python’s sort workspace use
O(n) auxiliary space. The result can occupy another O(n) space. The trace
recomputes prefix results for explanation; it is not the production scan.
Test boundaries and containment
Section titled “Test boundaries and containment”assert lower_bound([], 4) == 0assert lower_bound([5, 5, 5], 5) == 0assert lower_bound([2, 5], 1) == 0assert lower_bound([2, 5], 4) == 1assert lower_bound([2, 5], 6) == 2assert 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.")The search and interval boundary cases pass.Search possible answers with a feasibility test
Section titled “Search possible answers with a feasibility test”Binary search can search an ordered range of answers even when no input array
contains those answers. Suppose positive record sizes must stay in their
original order. Divide them into at most max_batches nonempty contiguous
batches, and minimize the largest batch total.
For a proposed capacity, fill the current batch until the next record would exceed that capacity. Then start another batch. This greedy scan uses the fewest batches for that capacity: moving a boundary earlier cannot let the first batch contain more records. Repeating that argument applies to each remaining suffix.
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 = 2low, 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 + 1answer_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))Bounds: (10, 32) Capacity: 21 Fits: TrueBounds: (10, 21) Capacity: 15 Fits: FalseBounds: (16, 21) Capacity: 18 Fits: TrueBounds: (16, 18) Capacity: 17 Fits: FalseMinimum capacity: 18One lower capacity fits: FalseIf a partition fits capacity c, the same partition fits every larger
capacity. This monotone predicate supplies the search order. The lower bound
cannot be smaller than the largest record, and the total fits in one batch.
Every iteration preserves the smallest feasible capacity within [low, high].
One predicate evaluation costs O(n). For search width
W = sum(sizes) - max(sizes), the complete function costs
O(n log(W + 2)) time and O(1) auxiliary space under constant-cost integer
arithmetic. Calling this algorithm O(log n) would omit the scan at every
candidate capacity.
assert minimum_batch_capacity([], 1) == 0assert minimum_batch_capacity([6], 4) == 6assert minimum_batch_capacity([2, 3, 4], 1) == 9assert minimum_batch_capacity([2, 3, 4], 3) == 4assert minimum_batch_capacity(record_sizes, batch_limit) == 18assert record_sizes == [7, 2, 5, 10, 8]print("Empty, single-record, batch-limit, and input-preservation checks pass.")Empty, single-record, batch-limit, and input-preservation checks pass.Practice
Section titled “Practice”An interval union includes the coverage of every input interval. A largest compatible subset solves a different problem. The greedy lesson selects intervals and proves why the earliest-finish rule maximizes their count.
Search Insert Position uses a boundary as the answer. State what the boundary means before you choose the comparison and update rules.
Merge Intervals tests ordering, containment, and endpoint policy. Include a fully contained interval in your manual trace.
Download the Python source to run the complete example locally.
Further reading
Section titled “Further reading”Python’s bisection documentation
defines the partition produced by bisect_left. Its performance notes explain
the separate cost of inserting into a list.
Python’s sorting guide
explains key functions and the distinction between sorted and list.sort.
Use it when an interview problem stores records instead of scalar values.