Binary Search: A Complete Crash Course
1) Binary Search
Binary search finds a target in a sorted array by checking the middle element and discarding the half that cannot contain the target. It runs in O(log n) time.
Each step works like this:
- If the middle value is too large, keep searching the left half
- If the middle value is too small, keep searching the right half
- If the middle value equals the target, you are done
The only requirement is that the search space is sorted, or at least ordered in a way that tells you which half to drop. It does not have to be an array at all.
2) Duplicates
Without duplicates, any index holding the target is the answer. With duplicates, a plain search may land on any copy.
Ask your interviewer which copy they want: the first one, the last one, or any of them. That choice decides which variation of binary search you write.
3) Variations of Binary Search
Every variation uses the same loop. Only the comparison and the pointer you move change.
Classic search returns as soon as it finds the target.
Leftmost occurrence keeps moving right toward the target and ends on its first copy.
Rightmost occurrence keeps moving left past the target and ends just after its last copy.
Search on a range looks for the smallest or largest value that satisfies a condition, even when there is no array.
4) Applications of Binary Search
Once you see binary search as "find the boundary where a condition flips", it shows up in many problems that never mention sorting:
- Searching a sorted matrix
- Finding a peak element
- Square roots
- Minimum speed or capacity problems
NOTES
Avoid overflow:
- In Java and C++, compute
mid = left + (right - left) / 2. Python integers do not overflow, so(left + right) // 2is fine.
Watch the loop:
- Decide whether the loop condition is
left <= rightorleft < right, and update the pointers to match, or the search can run forever.