Read-only web browser

Solutions

Browse the interview solutions folder with syntax highlighting.

binary-search.py

binary-search/binary-search.py · Python · 539 B · 2026-01-25 18:56

Back to folder
# Bisect the array to find the target value.

# O(log n) time | O(1) space
def binarySearch(nums: list[int], target: int) -> int:
    """
    >>> binarySearch([1,2,3,4,5], 3)
    2
    >>> binarySearch([1,2,3,4,5], 6)
    -1
    """
    left, right = 0, len(nums)-1
    while left <= right:
        mid = left + (right-left) //2 # or: left + right // 2
        curr = nums[mid]
        if curr == target:
            return mid
        elif curr < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1