SteelReed

Search

Search posts, questions…

Collections & DSAQuestion 18 / 25

Junior

What do you need before you can use binary search, and what are the usual implementation bugs?

Short answer

You need sorted data with O(1) index access; each step drops half, so it's O(log n).

YesNoa[mid] less than keya[mid] greater than keyequallo = 0, hi = n - 1lo ≤ hi?mid = lo + (hi - lo) / 2Return -(lo + 1)lo = mid + 1, loophi = mid - 1, loopReturn mid

3 points to say:

  1. 1 billion elements take only ~30 steps.
  2. Write mid = lo + (hi - lo) / 2 to avoid overflow.
  3. Wrong bound updates loop forever.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.