What is binary search?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Data Structures & Algorithms development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
Binary search is an efficient search algorithm for finding a target value in a sorted array in O(log n) time by repeatedly halving the search space. Algorithm: compare target to the middle element; if equal, found; if target < middle, search left half; if target > middle, search right half; repeat until found or search space is empty. Implementation: int left = 0, right = n-1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) return mid; if (arr[mid] < target) left = mid + 1; else right = mid - 1; } return -1;. Note: use left + (right - left) / 2 instead of (left + right) / 2 to avoid integer overflow. Time: O(log n). Space: O(1) iterative, O(log n) recursive (call stack). Precondition: array MUST be sorted. Variants: find first/last occurrence of a value (handle duplicates), find insertion position (lower_bound/upper_bound), search in rotated sorted array, binary search on the answer (find minimum speed, capacity, etc. using binary search on the answer space). Binary search reduces 1 billion elements to 30 comparisons (log₂(10⁹) ≈ 30).
Common Mistake
Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Data Structures & Algorithms answers easy to follow.