Skip to content
DSA in JavaScript
← All patterns

Modified Binary Search

0/19 solved

What it is

Cut the search space in half on every step by asking a yes/no question whose answer tells you which half to keep. It works on any monotonic condition, not only sorted arrays.

Used for

Sorted arrays, rotated arrays, "smallest value that works" problems, peak finding.
lo
hi

target = 23

Step 1 of 6

Goal: find 23 in this sorted list. Checking one number at a time could take 7 looks, and a million numbers would take up to a million. Because the list is sorted, we can do far better.

You see

  • Sorted or rotated input
  • Minimise the maximum or maximise the minimum
  • A yes/no check that flips once over a range

Learn it in

Linear SearchJump SearchInterpolation SearchBinary SearchSquare Root (Newton's Method)

Template

function firstTrue(lo, hi, ok) { // smallest x in [lo, hi] with ok(x)  while (lo < hi) {    const mid = (lo + hi) >> 1;    ok(mid) ? (hi = mid) : (lo = mid + 1);  }  return lo;}

Practice problems