Order and position
Episode 8 Binary Search
▶ This video is coming to YouTube soon.
The complete guide to binary search for coding interviews, in Java. 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 lo + (hi − lo) / 2, what it saves, Java's built-in tools, 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) / 2 overflows, and the safe middle
- Arrays.binarySearch, Collections.binarySearch, TreeSet 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
- 0:00Intro
- 0:24Halve the range
- 0:59A question that flips once
- 1:54Template 1: an exact value
- 2:52Template 2: where it flips
- 3:44The overflow bug
- 4:17What binary search saves
- 4:47Binary search in Java
- 5:46Five traps
- 6:30Nine binary search types
- 7:12Type 1 · Find a number in a sorted array
- 12:47Type 2 · Where does it fit?
- 18:37Type 3 · First and last position
- 24:48Type 4 · Smallest number in a rotated array
- 30:59Type 5 · Search in a rotated array
- 37:07Type 6 · Search a sorted grid
- 43:01Type 7 · Find a peak
- 49:07Type 8 · Slowest eating speed
- 55:29Type 9 · Time based key-value store
- 1:01:38Spot the type
- 1:02:23Quiz: which type?
- 1:03:11Recap