Skip to the good stuff
ELI5 Park
🎢 ELI5 Park / Binary Search / Binary Search
Easy

Binary Search

👶 The 5-Year-Old Summary

Guess a number between 1-100! I'll tell you "higher" or "lower". Smart strategy: always pick the middle, halving the possibilities each time!

🎮 Interactive Visualizer

Sorted Array: [-1, 0, 3, 5, 9, 12], Target: 9

🧠 The Brain Hack

left <= right is the loop condition! mid = (left + right) // 2 finds the middle! If target < nums[mid], go left (right = mid - 1). Else go right!

💻 The Clean Solution

def binary_search(nums, target):
    left, right = 0, len(nums) - 1
    
    while left <= right:
        mid = (left + right) // 2
        
        if nums[mid] == target:
            return mid
        elif nums[mid] < target:
            left = mid + 1  # Search right half
        else:
            right = mid - 1  # Search left half
    
    return -1  # Not found

# [-1, 0, 3, 5, 9, 12], target = 9
# Returns: 4

Time: O(log n)

Space: O(1)