๐ Introduction
Searching is one of the most common operations in programming, and binary search is the crown jewel โ fast, efficient, and widely applicable.
In this post, weโll explore:
โ Linear Search vs Binary Search
โ Binary search templates in Python
โ Real-world problems using binary search
โ Lower/Upper bound techniques
โ Searching in rotated arrays and 2D matrices
๐ 1๏ธโฃ Linear Search โ Simple but Slow**
def linear_search(arr, target): for i, num in enumerate(arr): if num == target: return i return -1
๐ฆ Time Complexity: O(n)
โ Best for small or unsorted arrays
โ Not efficient for large datasets
โก 2๏ธโฃ Binary Search โ Fast and Precise
Works on sorted arrays by dividing the search space in half at each step.
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
๐ฆ Time Complexity: O(log n)
โ Must be sorted
โ Used in both 1D and 2D problems
๐ 3๏ธโฃ Binary Search Template (Lower Bound Style)
This version is more flexible and forms the base of many variations.
def lower_bound(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
โ Finds the first position where target can be inserted.
๐งช 4๏ธโฃ Real Problems Using Binary Search
๐น Search Insert Position
def search_insert(nums, target): left, right = 0, len(nums) while left < right: mid = (left + right) // 2 if nums[mid] < target: left = mid + 1 else: right = mid return left
๐น Find First and Last Position of an Element
def find_first_last(nums, target): def find_bound(is_left): left, right = 0, len(nums) while left < right: mid = (left + right) // 2 if nums[mid] > target or (is_left and nums[mid] == target): right = mid else: left = mid + 1 return left left = find_bound(True) right = find_bound(False) - 1 if left <= right and right < len(nums) and nums[left] == target and nums[right] == target: return [left, right] return [-1, -1]
๐น Search in Rotated Sorted Array
def search_rotated(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]: if nums[left] <= target < nums[mid]: right = mid - 1 else: left = mid + 1 else: if nums[mid] < target <= nums[right]: left = mid + 1 else: right = mid - 1 return -1
๐น Binary Search in 2D Matrix
def search_matrix(matrix, target): if not matrix or not matrix[0]: return False m, n = len(matrix), len(matrix[0]) left, right = 0, m * n - 1 while left <= right: mid = (left + right) // 2 val = matrix[mid // n][mid % n] if val == target: return True elif val < target: left = mid + 1 else: right = mid - 1 return False
๐ฏ 5๏ธโฃ Advanced Use Cases
๐ธ Minimize the Maximum (Binary Search on Answer)
Use binary search on the value space, not index. Example:
- Minimum capacity to ship packages in D days Min max distance to place routers
Minimize largest subarray sum
๐ 6๏ธโฃ Comparison Summary
Method | Time | Use Case |
---|---|---|
Linear Search | O(n) | Unsorted or small datasets |
Binary Search | O(log n) | Sorted 1D arrays |
2D Binary Search | O(log m*n) | Sorted matrices |
Binary on Answer | Varies | Optimization problems |
โ Best Practices
โ๏ธ Always check if the array is sorted before applying binary search
โ๏ธ Use while left < right or while left <= right as per problem
โ๏ธ Avoid infinite loops: always update left/right
โ๏ธ Try implementing both upper and lower bound logic
โ๏ธ For rotated arrays โ think in terms of sorted halves
๐ง Summary
โ๏ธ Binary search is the go-to method for efficient searching in sorted data
โ๏ธ Understand different templates for flexible use
โ๏ธ Learn to use it in 1D, 2D, and even on value space
โ๏ธ A must-have technique for interviews and system optimization
๐ Coming Up Next:
๐ Part 8: Trees and Binary Trees โ Traversals, Depth, and Recursive Patterns
Weโll cover:
1. DFS & BFS - Inorder, Preorder, Postorder
- Balanced trees, height, diameter
- Binary Search Tree (BST) basics
Top comments (0)