#704

Binary Search

Easy Classic binary search

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Find the index of target in a sorted array, or return -1, in O(log n).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: find target in a sorted array in O(log n).

Why this works: compare with the middle; the target can only be in one half.

Example: [-1, 0, 3, 5, 9, 12], target 9

lo 0, hi 5 → mid 2 (3) < 9 → lo 3mid 4 (9) ✓ → index 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Writing lo = mid instead of lo = mid + 1, which can loop forever.

Solve on LeetCode ↗
Complexity
  • Time: O(log n).
  • Space: O(1).
Topic: Binary Search
🎬 Episodes 21–23: video coming soon