15 Binary Search Interview Questions and Answers
Prepare for your technical interview with our guide on Binary Search, featuring curated questions to enhance your algorithm understanding and problem-solving skills.
Prepare for your technical interview with our guide on Binary Search, featuring curated questions to enhance your algorithm understanding and problem-solving skills.
Binary Search is a fundamental algorithm in computer science, known for its efficiency in finding elements within sorted arrays. By repeatedly dividing the search interval in half, Binary Search significantly reduces the time complexity compared to linear search methods. This makes it an essential concept for optimizing search operations in various applications, from database indexing to real-time systems.
This article offers a curated selection of Binary Search interview questions designed to test and enhance your understanding of this critical algorithm. By working through these questions, you will gain the confidence and expertise needed to tackle Binary Search problems effectively in technical interviews.
Binary Search works by dividing the search space into halves, making it efficient for large datasets. The algorithm compares the target value to the middle element of a sorted array. If they match, the search is complete. If the target is less, the search continues on the left half; if greater, on the right half. This process repeats until the target is found or the search space is exhausted. The time complexity is O(log n), making it more efficient than linear search for large datasets.
Example:
def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 # Example usage: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] target = 5 print(binary_search(arr, target)) # Output: 4
Binary Search is more efficient than Linear Search in sorted datasets due to its O(log n) time complexity. Linear Search checks each element sequentially, resulting in O(n) time complexity, which is inefficient for large datasets. For example, in a sorted list of one million elements, Binary Search requires about 20 comparisons, while Linear Search may need up to one million.
Pseudocode for a standard Binary Search algorithm:
function binary_search(arr, target): low = 0 high = length(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid else if arr[mid] < target: low = mid + 1 else: high = mid - 1 return -1
Here is a Python implementation of a binary search function that returns the index of the first occurrence of a target value in a sorted array:
def binary_search_first_occurrence(arr, target): left, right = 0, len(arr) - 1 result = -1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: result = mid right = mid - 1 # Continue searching in the left half elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return result # Example usage: arr = [1, 2, 2, 2, 3, 4, 5] target = 2 print(binary_search_first_occurrence(arr, target)) # Output: 1
When dealing with a rotated sorted array, Binary Search can be applied by identifying the pivot point and determining which subarray contains the target value. The key steps are:
Example:
def search_rotated_array(nums, target): left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid if nums[left] <= nums[mid]: # Left side is sorted if nums[left] <= target < nums[mid]: right = mid - 1 else: left = mid + 1 else: # Right side is sorted if nums[mid] < target <= nums[right]: left = mid + 1 else: right = mid - 1 return -1 # Example usage: # nums = [4, 5, 6, 7, 0, 1, 2] # target = 0 # search_rotated_array(nums, target) # Output: 4
Binary search can be used to find the square root of a number by iteratively narrowing down the range of possible values. The idea is to start with a range from 0 to the number itself and repeatedly divide the range in half, checking whether the midpoint squared is less than, greater than, or equal to the target number. This process continues until the range is sufficiently small.
def binary_search_sqrt(x): if x < 0: raise ValueError("Cannot compute square root of a negative number") if x == 0 or x == 1: return x low, high = 0, x while low <= high: mid = (low + high) // 2 if mid * mid == x: return mid elif mid * mid < x: low = mid + 1 result = mid else: high = mid - 1 return result print(binary_search_sqrt(16)) # Output: 4 print(binary_search_sqrt(20)) # Output: 4
A mountain array first increases to a peak and then decreases. To find the peak element efficiently, use a binary search algorithm. If the middle element is greater than its neighbors, it is the peak. If the middle element is in the increasing part, the peak lies to the right; if in the decreasing part, to the left.
Example:
def find_peak_element(arr): left, right = 0, len(arr) - 1 while left < right: mid = (left + right) // 2 if arr[mid] < arr[mid + 1]: left = mid + 1 else: right = mid return left # Example usage mountain_arr = [1, 3, 5, 7, 6, 4, 2] peak_index = find_peak_element(mountain_arr) print(f"The peak element is at index: {peak_index}") # Output: The peak element is at index: 3
To find the smallest element in a rotated sorted array, use binary search. Compare the middle element with the rightmost element to decide which half to discard. If the middle element is greater than the rightmost, the smallest element is in the right half; otherwise, it’s in the left half.
def find_min_in_rotated_sorted_array(nums): left, right = 0, len(nums) - 1 while left < right: mid = (left + right) // 2 if nums[mid] > nums[right]: left = mid + 1 else: right = mid return nums[left] # Example usage: rotated_array = [4, 5, 6, 7, 0, 1, 2] print(find_min_in_rotated_sorted_array(rotated_array)) # Output: 0
To find the median of two sorted arrays using binary search, leverage the fact that the median is the middle value in a sorted list. By combining the two arrays and using binary search, you can efficiently find the median without fully merging the arrays.
def findMedianSortedArrays(nums1, nums2): if len(nums1) > len(nums2): nums1, nums2 = nums2, nums1 x, y = len(nums1), len(nums2) low, high = 0, x while low <= high: partitionX = (low + high) // 2 partitionY = (x + y + 1) // 2 - partitionX maxX = float('-inf') if partitionX == 0 else nums1[partitionX - 1] minX = float('inf') if partitionX == x else nums1[partitionX] maxY = float('-inf') if partitionY == 0 else nums2[partitionY - 1] minY = float('inf') if partitionY == y else nums2[partitionY] if maxX <= minY and maxY <= minX: if (x + y) % 2 == 0: return (max(maxX, maxY) + min(minX, minY)) / 2 else: return max(maxX, maxY) elif maxX > minY: high = partitionX - 1 else: low = partitionX + 1 raise ValueError("Input arrays are not sorted") # Example usage: nums1 = [1, 3] nums2 = [2] print(findMedianSortedArrays(nums1, nums2)) # Output: 2.0
To find the closest value to a given target in a sorted array, modify the binary search algorithm to track the closest value found during the search process.
def find_closest(arr, target): left, right = 0, len(arr) - 1 closest = arr[0] while left <= right: mid = (left + right) // 2 if abs(arr[mid] - target) < abs(closest - target): closest = arr[mid] if arr[mid] < target: left = mid + 1 elif arr[mid] > target: right = mid - 1 else: return arr[mid] return closest # Example usage: arr = [1, 3, 5, 7, 9, 11] target = 8 print(find_closest(arr, target)) # Output: 7
To determine if a number is a perfect square using binary search, apply the following logic:
low
and high
, to 1 and the number n
respectively.mid
of the interval.mid
is equal to n
. If it is, then n
is a perfect square.mid
is less than n
, move the low
pointer to mid + 1
.mid
is greater than n
, move the high
pointer to mid - 1
.Here is a concise implementation of this logic in Python:
def is_perfect_square(n): if n < 1: return False low, high = 1, n while low <= high: mid = (low + high) // 2 square = mid * mid if square == n: return True elif square < n: low = mid + 1 else: high = mid - 1 return False # Example usage: print(is_perfect_square(16)) # True print(is_perfect_square(14)) # False
To find the frequency of a target value in a sorted array, use binary search to find the first and last occurrence of the target value and then calculate the frequency.
def binary_search_first(arr, target): left, right = 0, len(arr) - 1 first_occurrence = -1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: first_occurrence = mid right = mid - 1 elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return first_occurrence def binary_search_last(arr, target): left, right = 0, len(arr) - 1 last_occurrence = -1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: last_occurrence = mid left = mid + 1 elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return last_occurrence def find_frequency(arr, target): first = binary_search_first(arr, target) if first == -1: return 0 last = binary_search_last(arr, target) return last - first + 1 # Example usage: arr = [1, 2, 2, 2, 3, 4, 5] target = 2 print(find_frequency(arr, target)) # Output: 3
Binary Search has several limitations:
To find the insertion point for a new element in a sorted array, binary search can be adapted to locate the position where the new element should be inserted to maintain the sorted order. The insertion point is the index at which the new element is greater than the previous element and less than the next element.
Example:
def binary_search_insertion_point(arr, target): left, right = 0, len(arr) while left < right: mid = (left + right) // 2 if arr[mid] < target: left = mid + 1 else: right = mid return left sorted_array = [1, 3, 5, 6] new_element = 4 insertion_point = binary_search_insertion_point(sorted_array, new_element) print(insertion_point) # Output: 2
The prerequisites for using Binary Search on a dataset are: