LeetEye LeetEye
Medium Binary Search ~5 min

Binary Search

binary-search binary-search

Problem

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

Examples

Example 1
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
9 exists in nums and its index is 4
Example 2
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
2 does not exist in nums so return -1
Key Insight

Sorted array = can eliminate half the search space with each comparison.

Sorted array: compare middle to target, eliminate half. Repeat until found or search space empty.

How to Approach This Problem

Pattern Recognition: When you see keywords like binary search binary-search, think Binary Search.

Step-by-Step Reasoning

1 Binary search is O(log n) because:
Answer: It halves the search space each iteration
n → n/2 → n/4 → ... → 1 takes log₂(n) steps.
2 Binary search requires the array to be:
Answer: Sorted
Without sorting, we can't eliminate half based on a single comparison.
3 To avoid integer overflow, the middle index should be:
Answer: left + (right - left) / 2
left + right can overflow for large indices. This formula avoids it.
4 If nums[mid] == target:
Answer: Return mid
We found it! Return the index.
5 We search the left half (right = mid - 1) when:
Answer: target < nums[mid]
Target is smaller than middle, so it must be in the smaller (left) portion.
6 The loop should continue while:
Answer: left <= right
When left == right, there's still one element to check. Loop ends when left > right (search space empty).

Solution

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

Complexity Analysis

Time O(log n)
Space O(1)

Master This Pattern

Build intuition with interactive MCQs. Practice Binary Search problems in the LeetEye app.

Download LeetEye Free
Practice in LeetEye