DSA Master › Topic 5
Binary Search
Binary search works on any monotonic yes/no predicate, not only on sorted arrays. If the predicate is false…false, true…true, you can find the first true in O(log n). That covers "minimum speed", "minimum capacity" and similar problems.
Concepts
- Lower/upper bounds
- Rotated arrays
- Binary search on the answer
- Monotonic predicates
How to recognise it
- The input is sorted, or sorted and rotated.
- The problem asks for the minimum or maximum value that makes something feasible.
- If X works, every larger (or smaller) X also works. That's a monotonic predicate.
Common pitfalls
- Pick one loop style (lo < hi or lo <= hi) and stick with it, or you'll hit off-by-one bugs.
- Use lo + (hi - lo) / 2 to avoid overflow, and use long inside feasible() when you add things up.
Problems
- Binary Search (Easy)
- Search Insert Position (Easy)
- First Bad Version (Easy)
- Find First and Last Position of Element in Sorted Array (Medium)
- Search in Rotated Sorted Array (Medium)
- Find Minimum in Rotated Sorted Array (Medium)
- Find Peak Element (Medium)
- Koko Eating Bananas (Medium)
- Capacity To Ship Packages Within D Days (Medium)
- Median of Two Sorted Arrays (Hard)
- Split Array Largest Sum (Hard)