Visualized DSA Strategies

Episode 8 Binary Search

1 h 9 min · JavaScript · Watch on YouTube

The complete guide to binary search for coding interviews, in JavaScript. First the idea: halve the range with every look, the two templates (an exact value, and where a yes or no question flips), the middle with Math.floor and why the bit shift (lo + hi) >> 1 wraps once the sum passes 2³¹, what it saves, why JavaScript has no binary search of its own (indexOf and findIndex scan) and the lowerBound you write instead, and five traps. Then nine types, each worked as a small problem in full: examples, the brute force animated beside the running line of code, the complete code, every line explained, and the binary search the same way.

What you'll learn

  • How binary search halves the range, and why it's O(log n)
  • The exact-value template: lo <= hi with mid ± 1
  • The lower-bound template: lo < hi with hi = mid, for any question that flips once
  • Why lo + hi can't overflow a JavaScript number, why (lo + hi) >> 1 wraps past 2³¹, and the safe middle with Math.floor
  • No built-in binary search: indexOf and findIndex scan in O(n), so write lowerBound for insertion points, counts, floor and ceiling
  • First and last position with two lower bounds
  • Rotated sorted arrays: the minimum, and search, by asking which half is sorted
  • A sorted grid as one long line, and a peak without sorting
  • Binary search on the answer, and searching a key's timestamps

Chapters