Binary Search With Lower Upper Bounds

Implement binary search with lower and upper bound variants for sorted array queries.

PythonData Integrity

Code

pythonsnippet
23 lines
def lower_bound(arr, target):
    lo, hi = 0, len(arr)
    while lo < hi:
        mid = (lo + hi) // 2
        if arr[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

def upper_bound(arr, target):
    lo, hi = 0, len(arr)
    while lo < hi:
        mid = (lo + hi) // 2
        if arr[mid] <= target:
            lo = mid + 1
        else:
            hi = mid
    return lo

def binary_search(arr, target):
    idx = lower_bound(arr, target)
    return idx if idx < len(arr) and arr[idx] == target else -1

How it works

Count the functions lower_bound, upper_bound and binary_search as the entire surface area of Binary Search With Lower Upper Bounds.

Repetition is confined to while lo < hi — the rest of the file is straight-line.

Using it

The main signature reads def lower_bound(arr, target)

Import lower_bound from the file and call it — the rest of the code is implementation detail.

Key statements

def binary_search(arr, target):
    idx = lower_bound(arr, target)
    return idx if idx < len(arr) and arr[idx] == target else -1
def lower_bound(arr, target):
    lo, hi = 0, len(arr)
    while lo < hi:
        mid = (lo + hi) // 2
        if arr[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo
def upper_bound(arr, target):
    lo, hi = 0, len(arr)
    while lo < hi:
        mid = (lo + hi) // 2
        if arr[mid] <= target:
            lo = mid + 1
        else:
            hi = mid
    return lo

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `lower_bound`, `upper_bound`, `binary_search` at load time.