Leetcode 704: Binary Search

A foundational $O(\log n)$ search algorithm for sorted arrays.

The original problem is here.

Intuition

Two-Pointer Approach

Algorithm

Binary search is effectively an inward-traversal two-pointer technique!

Termination

My solution

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

Complexity Analysis