Visualized DSA Strategies

Episode 8 Binary Search

1 h 7 min · Python

Title card of Episode 8: Binary Search

▶ This video is coming to YouTube soon.

The complete guide to binary search for coding interviews, in Python. First the idea: halve the range with every look, the two templates (an exact value, and where a yes or no question flips), why the middle is written lo + (hi − lo) // 2 even though Python's ints never overflow, what it saves, the bisect module (bisect_left, bisect_right and insort), 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, the search bisect_left runs
  • Why (lo + hi) // 2 can't overflow in Python but overflows in other languages, and the safe middle as a habit
  • bisect_left and bisect_right as lower and upper bound, counting copies, floor and ceiling, the key argument and insort
  • 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:28Halve the range
  3. 1:03A question that flips once
  4. 1:57Template 1: an exact value
  5. 3:06Template 2: where it flips
  6. 4:00The middle: a habit, not a bug
  7. 5:12What binary search saves
  8. 5:41Binary search in Python: bisect
  9. 7:20Five traps
  10. 8:16Nine binary search types
  11. 8:58Type 1 · Find a number in a sorted array
  12. 14:41Type 2 · Where does it fit?
  13. 20:39Type 3 · First and last position
  14. 27:07Type 4 · Smallest number in a rotated array
  15. 33:29Type 5 · Search in a rotated array
  16. 39:48Type 6 · Search a sorted grid
  17. 45:52Type 7 · Find a peak
  18. 51:59Type 8 · Slowest eating speed
  19. 58:33Type 9 · Time based key-value store
  20. 1:04:57Spot the type
  21. 1:05:43Quiz: which type?
  22. 1:06:30Recap