Searching Algorithms (DSA #8)
Finding one value in a million is either a million comparisons or twenty. The difference is whether the data is sorted. Binary search halves the remaining search space at every step, so it finds any element in an array of a million in about 20 comparisons, a billion in about 30. It is the highest-leverage algorithm in this course per line of code — and the one most people write with an off-by-one bug.
This chapter covers linear search, the binary-search template, the classic variants (first/last occurrence, rotated arrays), and the powerful generalization of binary search on the answer rather than the array.
Linear search
If the array is unsorted, there is no choice: inspect every element.
def linear_search(a, target):
for i, x in enumerate(a):
if x == target:
return i
return -1
\(O(n)\) time, \(O(1)\) space, works on any iterable. It is the baseline every other search must beat, and the fallback when sorting would cost more than the searches saved.
Binary search: halve the space
Binary search requires the array to be sorted. Keep a range [lo, hi] and check the middle:
def binary_search(a, target):
lo, hi = 0, len(a) - 1 # inclusive bounds
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1 # discard the left half
else:
hi = mid - 1 # discard the right half
return -1
The invariant is: if the target exists, it is always inside [lo, hi]. Each iteration shrinks the range by half, so there are \(\log_2 n\) iterations.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.62cm, minimum height=0.6cm, font=\small\bfseries}]
\foreach \v [count=\i from 0] in {2,5,8,12,16,23,38,56,72,91} {
\node[c, fill=blue!8] at (\i*0.68,0) {\v};
\node[font=\scriptsize\ttfamily] at (\i*0.68,-0.55) {\i};
}
\draw[thick, green!50!black] (-0.34,-0.38) rectangle (4.76,0.38);
\node[c, fill=orange!40, very thick] at (4*0.68,0.8) {23};
\draw[->, thick, orange!80!black] (4*0.68,0.55) -- (4*0.68,0.14);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (2.0,-1.0) {target 23: compare middle 16, search the right half};
\end{tikzpicture}
The mid bug. For very large lo + hi, integer overflow occurs in fixed-width languages; the safe form is lo + (hi - lo) // 2. Python’s integers do not overflow, but the habit is worth keeping.
The <= and boundary pitfalls
Two decisions cause most binary-search bugs:
- Inclusive vs exclusive bounds. Use inclusive
lo <= hiwithhi = len(a) - 1, or half-openlo < hiwithhi = len(a). Mixing them is the classic bug. - Which bound to move. To avoid infinite loops, always make progress:
lo = mid + 1orhi = mid - 1(notlo = mid).
When you need a boundary rather than a presence, use a lower/upper-bound template instead of returning early.
Variant: first and last occurrence
With duplicates, plain binary search returns some occurrence. To find the first, keep searching left after a hit; to find the last, keep searching right.
def first_occurrence(a, target):
lo, hi, ans = 0, len(a) - 1, -1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
ans = mid
hi = mid - 1 # keep looking left
elif a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return ans
The “answer” pattern — record a candidate and keep searching — also gives you “insertion point” (the first index where the value could go) and the count of a value (last - first + 1).
Variant: rotated sorted array
A sorted array rotated at some pivot (e.g. [4,5,6,7,0,1,2]) is still “half-sorted”: at every mid, at least one side is correctly sorted. Detect which side is sorted and decide where the target can lie.
def search_rotated(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[lo] <= a[mid]: # left half sorted
if a[lo] <= target < a[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half sorted
if a[mid] < target <= a[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1
This generalizes to “find the minimum in a rotated array”, a very common interview question.
Variant: binary search on the answer
The most valuable generalization: when the problem asks for a minimum or maximum value satisfying a monotonic condition, you can binary-search the answer space even when there is no sorted array. The condition \(P(x)\) must be monotone — true for all \(x\) above some threshold (or below it).
\[ \text{answer} = \min\{x : P(x)\} \quad\text{when } P \text{ is monotone} \]
A classic: ship packages within days days, minimising the ship capacity. Capacity is searchable: if capacity \(c\) works, any larger capacity also works.
def ship_within_days(weights, days):
def feasible(cap):
used, cur = 1, 0
for w in weights:
if cur + w > cap:
used += 1; cur = 0
cur += w
return used <= days
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = (lo + hi) // 2
if feasible(mid):
hi = mid # try smaller
else:
lo = mid + 1
return lo
The same shape solves “Koko eating bananas”, “split array largest sum”, “minimum days to make bouquets”, and “allocate books”. Whenever you can write a monotone feasible(x), binary search turns an \(O(n \cdot \text{range})\) problem into \(O(n \log \text{range})\).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
a/.style={->, thick, black!45}]
\draw[a] (0,0) -- (7.4,0) node[below, font=\small] {capacity $x$};
\draw[a] (0,0) -- (0,2.6) node[left, font=\small, align=right] {$P(x)$};
\draw[very thick, red!60] (0,2.2) -- (4.0,2.2) node[midway, above, font=\small] {infeasible};
\draw[very thick, green!55!black] (4.0,0.5) -- (7.2,0.5) node[midway, below, font=\small] {feasible};
\draw[dashed] (4.0,0) -- (4.0,2.4);
\node[font=\small, anchor=south] at (4.0,2.5) {answer};
\end{tikzpicture}
Pitfalls
- Off-by-one in
midor the bounds. Decide inclusive vs half-open and be consistent; thewhile lo <= hitemplate withhi = len - 1is the safest default. - Using binary search on unsorted data. It silently returns wrong answers; sort or choose another structure first.
- Returning on the first hit when you need a boundary. For first/last/count, keep searching after a match.
- Non-monotone feasibility. Binary search on the answer only works if
feasible(x)is monotone. Verify before using. - Integer overflow in
(lo+hi)//2. Uselo + (hi-lo)//2in fixed-width languages. - Ignoring the cost of sorting. If you search once, linear search may beat an \(O(n \log n)\) sort.
What invariant makes binary search correct? When can you binary-search an answer that is not in an array?
ASolution
The invariant is that the target (or the boundary) always lies within the current [lo, hi], and each step halves that range so it terminates in \(O(\log n)\). You can binary-search an answer when a predicate feasible(x) is monotone — true for all values above a threshold or all below it — so you can discard half the answer space at each step.
Next: Binary Trees and Traversals (DSA #9) — the hierarchical structure and the four ways to walk it.