Binary Search

Search for a target in a sorted array.

Pattern

Classic Binary Search

This problem follows the Classic Binary Search pattern, commonly found in the Binary Search category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Compare target with mid. Narrow to left or right half accordingly.

Key Insight

The key is the loop invariant: the target, if it exists, is always in [left, right]. Each iteration halves this range.

Step-by-step

  1. 1Set left = 0, right = len(nums) - 1
  2. 2While left <= right:
  3. 3Calculate mid = (left + right) // 2
  4. 4If nums[mid] == target, return mid
  5. 5If nums[mid] < target, search right half (left = mid + 1)
  6. 6Else search left half (right = mid - 1)

Pseudocode

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
    else:
        right = mid - 1
return -1
Complexity Analysis

Time Complexity

O(log n)

Space Complexity

O(1)
More Binary Search Problems

Master this pattern with YeetCode

Practice Binary Search and similar Binary Search problems with flashcards. Build pattern recognition through active recall.

Practice this problem