Data Structures & Algorithms Binary Search
💡
Exercise 47

Binary Search Concept 10 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Binary Search is one of the most important algorithms in computer science. It finds an element in a sorted array in O(log n) time! 🔍

💡 Think of it like this: You're playing a number guessing game. The number is between 1-100. Instead of guessing 1, 2, 3... you guess 50! "Too high" → try 25. "Too low" → try 37. Each guess eliminates HALF the remaining numbers!

💭 Now it's your turn! Using the approach above, implement your solution in the editor. You've got this! 💪

Step-by-step trace for arr=[1,3,5,7,9,11], target=7:

  • left=0, right=5, mid=2 → arr[2]=5 < 7 → search right half, left=3
  • left=3, right=5, mid=4 → arr[4]=9 > 7 → search left half, right=3
  • left=3, right=3, mid=3 → arr[3]=7 == 7 → FOUND at index 3!

Why O(log n)? We cut the search space in half each time. For 1,000,000 elements, we need at most ~20 comparisons (log₂ 1,000,000 ≈ 20). Compare to O(n) linear search needing up to 1,000,000 comparisons!

When to use binary search:

  • ✅ Array must be sorted
  • ✅ Looking for a specific value
  • ✅ Finding boundary (first/last occurrence)
  • ✅ Any "find minimum that satisfies condition" problem
📋 Instructions
Implement `binary_search(nums, target)` that returns the index of target, or -1 if not found. Test with: - `binary_search([-1,0,3,5,9,12], 9)` → 4 - `binary_search([-1,0,3,5,9,12], 2)` → -1 Print both results.
Classic binary search: left=0, right=len-1, while left<=right, mid=(left+right)//2, compare and adjust boundaries.
⚠️ Try solving it yourself first — you'll learn more!
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    
    while left <= right:
        mid = (left + right) // 2
        
        if arr[mid] == target:
            return mid           # Found it!
        elif arr[mid] < target:
            left = mid + 1       # Target is in right half
        else:
            right = mid - 1      # Target is in left half
    
    return -1  # Not found
🧪 Test Cases
Input
binary_search([-1,0,3,5,9,12], 9)
Expected
4
Test case 1
Input
binary_search([-1,0,3,5,9,12], 2)
Expected
-1
Boundary value
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.