Binary search is a fundamental algorithm that every programmer should master. Not only is it incredibly efficient for searching sorted arrays, but it also forms the basis for many advanced problem-solving techniques. In this blog post, we'll explore various binary search patterns that frequently appear in coding interviews.
Let's start with the classic implementation:
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
This algorithm works on a sorted array by repeatedly dividing the search interval in half:
[ 1 | 3 | 5 | 7 | 9 | 11 | 13 | 15 ]
^ ^ ^
left mid right