The "Binary Search interview question" is the quintessential algorithm for efficiently finding an element in a sorted array. Instead of checking every element one by one (linear search), Binary Search repeatedly divides the search interval in half. If the target value is less than the value in the middle of the interval, you narrow the interval to the lower half. Otherwise, you narrow it to the upper half.
This is a "must-know" for any software engineer. Companies from Apple to Google ask the "Binary Search coding problem" to verify a candidate's understanding of logarithmic time complexity (). It tests your ability to manage pointers, avoid infinite loops, and handle the "midpoint" calculation correctly to prevent integer overflow.
This problem is the foundation of the Binary Search pattern.
left = 0 and right = n - 1.left <= right:
mid = left + (right - left) / 2.arr[mid] == target, return mid.arr[mid] < target, move left = mid + 1.arr[mid] > target, move right = mid - 1.Array: [-1, 0, 3, 5, 9, 12], Target: 9
left = 0, right = 5. mid = 2 (Value: 3).left = 3, right = 5.mid = 4 (Value: 9).(left + right) / 2 instead of left + (right - left) / 2.left < right instead of left <= right, which can cause the algorithm to miss the target if it’s at the very end of the range.left = mid or right = mid instead of mid + 1 or mid - 1, which can lead to infinite loops.Binary Search isn't just for finding a number. It can be used on any "sorted" or monotonic space, such as finding a square root or the best price in a range. Master the basic "Binary Search" first, then practice its "Search Insert Position" or "Find First and Last" variations.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Search Insert Position | Easy | Solve | |
| Find Smallest Letter Greater Than Target | Easy | Solve | |
| Kth Missing Positive Number | Easy | Solve | |
| Check If a Number Is Majority Element in a Sorted Array | Easy | Solve | |
| Fixed Point | Easy | Solve |