Searching Algorithms (Linear & Binary Search)
📖 Concept
Searching is the other fundamental algorithm category. The leap from O(n) linear search to O(log n) binary search is one of the most important optimizations in computing.
Linear Search — O(n):
- Check each element one by one
- Works on unsorted data
- Best for small arrays or one-time searches
Binary Search — O(log n):
- Requires sorted data
- Halves search space each step
- log₂(1,000,000) ≈ 20 — only 20 comparisons for a million elements!
Binary search template (the bug-free version):
lo = 0, hi = n - 1
while (lo <= hi):
mid = lo + (hi - lo) / 2
if found: return mid
if target > mid: lo = mid + 1
else: hi = mid - 1
Binary search variants:
- Find exact value
- Find first occurrence (leftmost)
- Find last occurrence (rightmost)
- Find insertion point (lower bound / upper bound)
- Search on answer (binary search on the answer space)
🏠 Real-world analogy: Linear search is reading a phone book one name at a time. Binary search is opening to the middle, deciding if your name is before or after, then doing the same on the half — like how you actually use a dictionary.
💻 Code Example
1// LINEAR SEARCH — O(n)2function linearSearch(arr: number[], target: number): number {3 for (let i = 0; i < arr.length; i++) {4 if (arr[i] === target) return i;5 }6 return -1;7}89// BINARY SEARCH — O(log n), standard template10function binarySearch(arr: number[], target: number): number {11 let lo = 0, hi = arr.length - 1;12 while (lo <= hi) {13 const mid = lo + Math.floor((hi - lo) / 2);14 if (arr[mid] === target) return mid;15 if (arr[mid] < target) lo = mid + 1;16 else hi = mid - 1;17 }18 return -1;19}2021// FIND FIRST OCCURRENCE (leftmost)22function findFirst(arr: number[], target: number): number {23 let lo = 0, hi = arr.length - 1, result = -1;24 while (lo <= hi) {25 const mid = lo + Math.floor((hi - lo) / 2);26 if (arr[mid] === target) {27 result = mid; // Found, but keep searching left28 hi = mid - 1;29 } else if (arr[mid] < target) lo = mid + 1;30 else hi = mid - 1;31 }32 return result;33}3435// FIND LAST OCCURRENCE (rightmost)36function findLast(arr: number[], target: number): number {37 let lo = 0, hi = arr.length - 1, result = -1;38 while (lo <= hi) {39 const mid = lo + Math.floor((hi - lo) / 2);40 if (arr[mid] === target) {41 result = mid; // Found, but keep searching right42 lo = mid + 1;43 } else if (arr[mid] < target) lo = mid + 1;44 else hi = mid - 1;45 }46 return result;47}4849// SEARCH IN ROTATED SORTED ARRAY50function searchRotated(nums: number[], target: number): number {51 let lo = 0, hi = nums.length - 1;52 while (lo <= hi) {53 const mid = lo + Math.floor((hi - lo) / 2);54 if (nums[mid] === target) return mid;5556 if (nums[lo] <= nums[mid]) { // Left half is sorted57 if (target >= nums[lo] && target < nums[mid]) hi = mid - 1;58 else lo = mid + 1;59 } else { // Right half is sorted60 if (target > nums[mid] && target <= nums[hi]) lo = mid + 1;61 else hi = mid - 1;62 }63 }64 return -1;65}6667// BINARY SEARCH ON ANSWER — "Find minimum X such that condition is true"68// Example: minimum capacity to ship packages in D days69function shipWithinDays(weights: number[], days: number): number {70 let lo = Math.max(...weights);71 let hi = weights.reduce((a, b) => a + b, 0);7273 while (lo < hi) {74 const mid = lo + Math.floor((hi - lo) / 2);75 if (canShip(weights, days, mid)) hi = mid;76 else lo = mid + 1;77 }78 return lo;79}8081function canShip(weights: number[], days: number, capacity: number): boolean {82 let daysNeeded = 1, currentLoad = 0;83 for (const w of weights) {84 if (currentLoad + w > capacity) {85 daysNeeded++;86 currentLoad = 0;87 }88 currentLoad += w;89 }90 return daysNeeded <= days;91}
🏋️ Practice Exercise
Practice Problems (Easy → Hard):
- Implement binary search (iterative and recursive)
- Find the first and last position of a target in a sorted array
- Search in a rotated sorted array
- Find the square root of a number using binary search (integer)
- Find peak element in an array (element greater than neighbors)
- Find minimum in a rotated sorted array
- Search a 2D sorted matrix using binary search
- Koko eating bananas — binary search on answer
- Split array largest sum — binary search on answer
- Median of two sorted arrays — O(log(min(m,n)))
⚠️ Common Mistakes
Off-by-one errors: using
lo < hiwhen you needlo <= hi(or vice versa)Integer overflow in
(lo + hi) / 2— uselo + (hi - lo) / 2insteadApplying binary search to unsorted data — it REQUIRES sorted input (or a monotonic condition)
Not handling duplicates properly — standard binary search finds ANY occurrence, not first/last
Forgetting the 'binary search on answer' pattern — many optimization problems use it
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for Searching Algorithms (Linear & Binary Search)