Leetcode 704: Binary Search

The original question can be found here.

The question is asking us to perform a binary search on an sorted array, which is a classical algorithm. If you haven’t, please visit my another post which detailed describe this algorithm.

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        if not nums:
            return -1
        
        left, right = 0, len(nums) - 1
        while left + 1 < right:
            mid = (left + right) // 2
            if nums[mid] == target:
                return mid
            elif nums[mid] < target:
                left = mid
            else:
                right = mid
        
        if nums[left] == target:
            return left
        
        if nums[right] == target:
            return right
        
        return -1

Time complexity: O(logn). Space complexity: O(1).

Scroll to Top