Binary Search (LeetCode #4)
Binary search finds an element in a million in about twenty steps by throwing away half the possibilities each time. It is also the algorithm most people get subtly wrong. This post covers the seven NeetCode Binary Search problems, including the two variants that matter most: searching a rotated array and searching on the answer.
The technique
Keep two indices lo, hi that always bracket the answer, and halve the range each step.
def binary_search(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi: # inclusive range [lo, hi]
mid = lo + (hi - lo) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
Two rules. Decide whether your range is inclusive (hi = len-1, lo <= hi, move to mid ± 1) or half-open (hi = len, lo < hi, move to mid), and never mix them. When the answer is a boundary rather than an exact value, do not return on a match — record it and keep searching.
Search on the answer. If the problem asks for the smallest value satisfying a monotone property, binary-search the value itself even without a sorted array.
\[ \text{answer} = \min\{x : \text{feasible}(x)\} \]
Binary Search
The question. Given a sorted array and a target, return its index or -1.
def binary_search(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target: return mid
if nums[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1
\(O(\log n)\) time, \(O(1)\) space.
Search a 2D Matrix
The question. A matrix has rows sorted left-to-right and each row’s first element greater than the previous row’s last. Find a target, in \(O(\log(mn))\).
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: True
The idea. Because the rows are stacked in order, the whole matrix is one sorted 1-D array of length m·n. Map a flat index mid to a cell with row = mid // n, col = mid % n, and binary-search the flat index.
Walk it through on the matrix with m=3, n=4: flat index 0→(0,0)=1, 1→(0,1)=3, …, 6→(1,2)=16. Searching 3 finds flat index 1.
def search_matrix(matrix, target):
m, n = len(matrix), len(matrix[0])
lo, hi = 0, m * n - 1
while lo <= hi:
mid = (lo + hi) // 2
val = matrix[mid // n][mid % n] # flat -> 2D
if val == target: return True
if val < target: lo = mid + 1
else: hi = mid - 1
return False
\(O(\log(mn))\) time, \(O(1)\) space. An alternative is to binary-search the row, then the column.
Koko Eating Bananas
The question. Each hour Koko eats from one pile at speed k; finish all piles within h hours. Find the smallest k.
Input: piles = [3,6,7,11], h = 8
Output: 4 (hours = 1 + 2 + 2 + 3 = 8)
The idea. No sorted array, but the predicate “can finish at speed k” is monotone: if k works, any larger speed works. Binary-search the smallest feasible k. Each pile takes ceil(p / k) = (p + k - 1) // k hours.
Walk it through. k=6 → 6 hours ≤ 8, feasible; k=3 → 10 > 8, too slow; k=5 → 8, feasible; k=4 → 8, feasible → answer 4.
\begin{tikzpicture}[font=\rmfamily, >=stealth]
\draw[->, thick] (0,0) -- (4.4,0) node[font=\scriptsize\ttfamily, anchor=north] at (4.4,-0.05) {k};
\draw[->, thick] (0,0) -- (0,2.2) node[font=\scriptsize\ttfamily, anchor=east] at (-0.05,2.2) {hours};
\draw[thick, blue!70!black] (0.4,1.9) -- (3.9,0.4);
\draw[dashed, thick, black!40] (0,1.05) -- (4.2,1.05);
\fill[green!60!black] (2.6,0.72) circle (0.07);
\node[font=\scriptsize\ttfamily, anchor=north] at (2.6,-0.15) {first feasible};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (2.1,-0.6) {slower -> feasible; binary search the boundary};
\end{tikzpicture}
def min_eating_speed(piles, h):
def feasible(k):
return sum((p + k - 1) // k for p in piles) <= h # ceil division
lo, hi = 1, max(piles)
while lo < hi:
mid = (lo + hi) // 2
if feasible(mid): hi = mid
else: lo = mid + 1
return lo
\(O(n \log(\max \text{pile}))\) time, \(O(1)\) space.
Find Minimum in Rotated Sorted Array
The question. A sorted array was rotated; return the minimum, in \(O(\log n)\).
Input: [3,4,5,1,2] -> 1
The idea. Compare a[mid] with a[hi]. If a[mid] > a[hi], the minimum is strictly right of mid; otherwise it is at mid or left.
Walk it through on [3,4,5,1,2]: mid=2 (5) > 2 → lo=3; mid=3 (1) < 2 → hi=3; lo==hi → a[3]=1.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
\foreach \v [count=\i from 0] in {3,4,5,1,2} { \node[c, fill=blue!8] at (\i*0.66,0) {\v}; }
\draw[very thick, green!55!black, rounded corners=2pt] (-0.37,-0.32) rectangle (1.6,0.32);
\node[font=\scriptsize\ttfamily, text=green!45!black, anchor=north] at (0.62,-0.4) {sorted};
\node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=north] at (2.3,-0.4) {min lives here};
\end{tikzpicture}
def find_min(a):
lo, hi = 0, len(a) - 1
while lo < hi:
mid = (lo + hi) // 2
if a[mid] > a[hi]: lo = mid + 1
else: hi = mid # mid could BE the minimum
return a[lo]
\(O(\log n)\) time, \(O(1)\) space.
Search in Rotated Sorted Array
The question. Search a rotated sorted array in \(O(\log n)\).
Input: [4,5,6,7,0,1,2], target = 0 -> 4
The idea. At every mid, at least one half is properly sorted. Detect which (a[lo] <= a[mid] means the left half), and if the target lies in its value range, search there; otherwise search the other half.
Walk it through for target 0 on [4,5,6,7,0,1,2]: mid=3 (7), left [4,5,6,7] sorted, 0 not in [4,7] → right half; mid=5 (1), right [1,2] sorted, 0 not in [1,2] → left; mid=4 (0) → found.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
\foreach \v [count=\i from 0] in {4,5,6,7,0,1,2} { \node[c, fill=blue!8] at (\i*0.66,0) {\v}; }
\draw[very thick, green!55!black, rounded corners=2pt] (-0.37,-0.32) rectangle (2.28,0.32);
\draw[very thick, orange!80!black, rounded corners=2pt] (2.29,-0.32) rectangle (4.25,0.32);
\node[font=\scriptsize\ttfamily, text=green!45!black, anchor=north] at (0.95,-0.4) {sorted half};
\node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=north] at (3.27,-0.4) {target here};
\end{tikzpicture}
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
\(O(\log n)\) time, \(O(1)\) space.
Time Based Key-Value Store
The question. Design a store with set(key, value, timestamp) and get(key, timestamp), where get returns the value with the largest timestamp ≤ the query. Timestamps are strictly increasing per key.
set("foo", "bar", 1); get("foo", 1) -> "bar"; get("foo", 3) -> "bar"
The idea. For each key keep a list of (timestamp, value) pairs, appended in increasing order. A get is “the last entry with timestamp ≤ query”, a binary search for the rightmost position.
Walk it through. set("foo","bar",1), set("foo","baz",4). get("foo",3) → timestamps [1,4], the largest ≤ 3 is 1 → "bar". get("foo",5) → 4 → "baz".
import bisect
from collections import defaultdict
class TimeMap:
def __init__(self):
self.store = defaultdict(list) # key -> [(ts, value)]
def set(self, key, value, timestamp):
self.store[key].append((timestamp, value))
def get(self, key, timestamp):
pairs = self.store[key]
i = bisect.bisect_right(pairs, (timestamp, chr(127))) # rightmost ts <= query
return pairs[i - 1][1] if i else ""
Why bisect_right? It returns the insertion point after every entry with timestamp ≤ the query, so i - 1 is the desired entry. The chr(127) sentinel makes the tuple compare greater than any real value at that timestamp.
\(O(1)\) set, \(O(\log n)\) get.
Median of Two Sorted Arrays
The question. Return the median of two sorted arrays in \(O(\log(\min(m,n)))\).
Input: a = [1,3], b = [2] -> 2.0
Input: a = [1,2], b = [3,4] -> 2.5
The idea. Partition the combined data into an equal-size left and right half such that every left element ≤ every right element. If we take i elements from a, the count from b is fixed. Binary-search i until the partition is valid (the four boundary values satisfy left_a ≤ right_b and left_b ≤ right_a).
Walk it through on [1,3], [2] (total 3, left half 2 elements). i=1 from a → left [1], so j=1 from b → left [1,2], right [3]. Check 1 ≤ ∞ and 2 ≤ 3 — valid. Odd total → median is max(1,2) = 2.
def find_median(a, b):
if len(a) > len(b):
a, b = b, a # search the smaller array
m, n = len(a), len(b)
lo, hi = 0, m
while lo <= hi:
i = (lo + hi) // 2
j = (m + n + 1) // 2 - i
left_a = a[i-1] if i > 0 else float("-inf")
right_a = a[i] if i < m else float("inf")
left_b = b[j-1] if j > 0 else float("-inf")
right_b = b[j] if j < n else float("inf")
if left_a <= right_b and left_b <= right_a:
if (m + n) % 2:
return max(left_a, left_b)
return (max(left_a, left_b) + min(right_a, right_b)) / 2
if left_a > right_b: hi = i - 1
else: lo = i + 1
\(O(\log(\min(m,n)))\) time, \(O(1)\) space.
Pitfalls
- Off-by-one in the bounds. Commit to inclusive or half-open and stay consistent.
- Returning on a hit when you need a boundary. Keep searching.
- Non-monotone feasibility. Binary search on the answer requires a monotone predicate.
- Flat-to-2D indexing.
row = mid // n,col = mid % n(withn= number of columns). - Searching the longer array in the median problem. Shrink to the smaller for the log bound.
What invariant keeps binary search correct, and when can you binary-search an answer not in an array?
ASolution
The answer always lies within the current [lo, hi], and each step halves it. You can binary-search an answer when a predicate feasible(x) is monotone — true above (or below) a threshold — so half the answer space can be discarded each step.
Next: Sliding Window (LeetCode #5) — a window that only ever moves forward.