Binary Search With Lower Upper Bounds
Implement binary search with lower and upper bound variants for sorted array queries.
Code
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 -1How 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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.