Visualized DSA Strategies

Episode 8 Binary Search

1 h 9 min · PHP

Title card of Episode 8: Binary Search

▶ This video is coming to YouTube soon.

The complete guide to binary search for coding interviews, in PHP. First the idea: halve the range with every look, the two templates (an exact value, and where a yes or no question flips), how to compute the middle in PHP (intdiv, because a slash gives a float, and what overflow does to 64-bit ints), what it saves, why PHP has no binary search of its own (array_search and in_array scan), 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 the middle is $lo + intdiv($hi - $lo, 2): a slash gives a float, and past PHP_INT_MAX a sum turns into one
  • No built-in binary search in PHP: array_search and in_array scan, so you write lowerBound
  • 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

  1. 0:00Intro
  2. 0:30Halve the range
  3. 1:06A question that flips once
  4. 2:00Template 1: an exact value
  5. 3:13Template 2: where it flips
  6. 4:12The middle: intdiv, not a slash
  7. 5:49What binary search saves
  8. 6:19Binary search in PHP: write lowerBound
  9. 8:02Five traps
  10. 9:07Nine binary search types
  11. 9:49Type 1 · Find a number in a sorted array
  12. 15:36Type 2 · Where does it fit?
  13. 21:33Type 3 · First and last position
  14. 28:23Type 4 · Smallest number in a rotated array
  15. 34:55Type 5 · Search in a rotated array
  16. 41:07Type 6 · Search a sorted grid
  17. 47:11Type 7 · Find a peak
  18. 53:19Type 8 · Slowest eating speed
  19. 1:00:00Type 9 · Time based key-value store
  20. 1:06:29Spot the type
  21. 1:07:14Quiz: which type?
  22. 1:08:02Recap