roadmap/Binary Search

Topic 5 / 16

Binary Search

MediumSearch~4 days
Easy to grasp
progress0 / 14 solved

Halve the search space each iteration. Works on sorted arrays and answer-space problems.

Repeatedly halve the search space by comparing the target to the midpoint. Requires sorted input or a monotonic predicate. Classic binary search finds an exact value; generalized binary search finds the boundary where a condition flips from false to true. Binary search on answer treats the answer space as the array.

  • โ—†Array is sorted or has a monotonic property
  • โ—†Find minimum/maximum value that satisfies a condition
  • โ—†Search in rotated sorted array
  • โ—†Real-valued binary search (floating point answers)
  • โ—†Koko eating bananas / capacity ship packages style problems
Classic โ€” find target
lo=0, hi=n-1. Return mid when arr[mid]==target.
Left boundary
Find first position where condition is true. Use lo=mid+1 when false.
Right boundary
Find last position where condition is true. Use hi=mid-1 when true.
Binary search on answer
Define a feasibility function; binary search the answer range.
Binary search โ€” target = 13
1
0
3
1
5
2
7
3
9
mid
11
5
13
6
15
7
17
8
19
9
lo=0mid=4hi=9arr[mid] < target โ†’ move lo right
step 1 / 4
Brute force
Linear scan through sorted array โ†’ O(n).
Observation
Sorted order lets us eliminate half the array at each comparison.
Optimization
lo/hi pointers. mid = lo + (hi - lo) / 2. Move the pointer that can't contain the answer.
Final complexity
O(log n) โ€” search space halves every iteration.

Why should you use lo + (hi - lo) / 2 instead of (lo + hi) / 2?

Binary search on the answer space requires what property of the feasibility function?

In a rotated sorted array, how do you determine which half is sorted?

Check each question you can answer confidently before moving to the next topic.

Progress is saved on this device