DSA & CS / 4. BINARY SEARCH
Binary Search
Eliminate half the search space every step — O(log n)
EXPLANATION
Binary search works on sorted arrays. Each step eliminates half the remaining search space — that's what gives O(log n). The tricky part isn't the algorithm — it's the boundary conditions. Off-by-one errors are extremely common. Use this template consistently: Classic template: left=0, right=len-1, while left <= right, mid = left + (right-left)//2 The real power: binary search isn't just for finding exact values. It applies whenever: • You can define a monotonic condition (true/false boundary) • You're searching for a minimum/maximum that satisfies a condition • "Find the first/last position of X" • "Minimum capacity to ship in D days" • "Koko eating bananas" When you see: "find minimum X such that condition(X) is true" → think binary search on the answer, not the array.
DIAGRAM
Find 7 in [1, 3, 5, 7, 9, 11, 13]: L=0, R=6, mid=3 → arr[3]=7 → found! Find 6: L=0, R=6, mid=3 → arr[3]=7 > 6 → R=mid-1=2 L=0, R=2, mid=1 → arr[1]=3 < 6 → L=mid+1=2 L=2, R=2, mid=2 → arr[2]=5 < 6 → L=mid+1=3 L=3 > R=2 → not found Binary search on answer: "Minimum speed to eat all bananas in H hours" → search space: [1, max(piles)] → check: can_finish(speed) → True/False boundary
CODE