Kodewick
Start learning →
Patterns: searching40 / 52

Patterns: searching

Lesson 40 of 52 · Part 7 · Searching · about 20 minutes

This chapter 6 review shows that binary search needs not a sorted list but a condition that turns from False to True exactly once, and uses it three ways: binary search on the answer, on a rotated sorted array, and on a condition such as the first bad version.

There seem to be many binary search problems: the square root of x, the least capacity to ship packages, Koko eating bananas, searching a rotated array, finding a peak, the first bad version… Yet they all rest on one thing: each look tells you which half the answer is in. What you need is not "the list is sorted" but a condition that turns from False to True exactly once. Find that condition and it is the lower bound of the last two lessons: O(log n).

Pattern 1: binary search on the answer

The integer square root of n is the largest k with k × k ≤ n. Line up the squares of 0, 1, 2, 3…: they go from small to large, and we want the first k whose square is > n, minus 1. This "array" never has to be built: to look at entry mid, just compute mid * mid.

k × k (n = 8; the array isn't built, each entry is computed when needed)014916253649640123456789↑lo↑hi
1lo, hi = 0, n + 12while lo < hi:3    mid = (lo + hi) // 24    if mid * mid <= n:5        lo = mid + 16    else:7        hi = mid8return lo - 1

The integer square root of 8: the boxes hold k × k (the index is k), find the first one > 8. 3 looks find k = 3, and the answer is 3 − 1 = 2

The same idea in a more interview-like place: the least ship capacity that ships all packages within d days. Packages are loaded in order, each day until the next one doesn't fit. The bigger the capacity, the fewer days: "is capacity c enough?" is False for small c and True from some c on. The answer lies between max(weights) (the heaviest package must fit) and sum(weights) (all in one day); binary search on it, checking each guess with an O(n) simulation:

main.py
1def isqrt(n):                         # the largest k with k * k <= n2    lo, hi = 0, n + 1                 # find the first k with k * k > n3    looks = 04    while lo < hi:5        mid = (lo + hi) // 26        looks += 17        if mid * mid <= n:8            lo = mid + 19        else:10            hi = mid11    return lo - 1, looks12 13for n in [8, 99, 100, 2_000_000_000]:14    print("isqrt(%d) =" % n, isqrt(n))15 16def days_needed(weights, cap):        # how many days capacity cap takes17    days, load = 1, 018    for w in weights:19        if load + w > cap:            # doesn't fit today: tomorrow20            days += 121            load = 022        load += w23    return days24 25checks = 026def ok(weights, d, cap):27    global checks28    checks += 129    return days_needed(weights, cap) <= d30 31def ship_linear(weights, d):          # try capacities one by one from the smallest32    cap = max(weights)33    while not ok(weights, d, cap):34        cap += 135    return cap36 37def ship_binary(weights, d):          # find the first capacity that is enough38    lo, hi = max(weights), sum(weights)39    while lo < hi:40        mid = (lo + hi) // 241        if ok(weights, d, mid):42            hi = mid43        else:44            lo = mid + 145    return lo46 47w = list(range(1, 51))                # 50 packages weighing 1 to 5048for f in [ship_linear, ship_binary]:49    checks = 050    print(f.__name__, "least capacity for 3 days:", f(w, 3), "checks:", checks)
Output
isqrt(8) = (2, 3)
isqrt(99) = (9, 7)
isqrt(100) = (10, 7)
isqrt(2000000000) = (44721, 31)
ship_linear least capacity for 3 days: 435 checks: 386
ship_binary least capacity for 3 days: 435 checks: 11

Trying one by one takes 386 checks, binary search only 11 (the range is 50 to 1275, log₂ 1225 ≈ 10.3). The total time is O(n log S), where S is the size of the answer's range. The sentence that gives this pattern away is "the smallest … such that …" or "the largest … such that …": first write the function "given an answer, does it work?", make sure it is monotonic, then apply lower bound.

Choose one

The packages [3, 2, 2, 4, 1, 4] are loaded in order and must all ship within 3 days. What is the smallest capacity?

Exercise 1

The slowest banana-eating speed

There are piles of bananas piles, to be eaten within h hours. The speed is k bananas an hour: each hour you eat from one pile only, and a pile with fewer than k still uses up that hour. Complete min_speed(piles, h): return the smallest k that finishes in time (h is promised to be at least the number of piles).

It should print
4
30 23
500000000
exercise1.py
1def hours(piles, k):                  # how many hours speed k takes2    return sum((p + k - 1) // k for p in piles)3 4def min_speed(piles, h):5    lo, hi = 1, max(piles)6    # find the first k with hours(piles, k) <= h7    return hi8 9print(min_speed([3, 6, 7, 11], 8))10print(min_speed([30, 11, 23, 4, 20], 5), min_speed([30, 11, 23, 4, 20], 6))11print(min_speed([1000000000], 2))
Output
Press Run or Ctrl+Enter

Pattern 2: a rotated sorted array

A sorted array is cut somewhere and its two parts swapped, like [15, 18, 22, 3, 6, 9, 12]. The whole isn't sorted, but cut at mid, at least one of the two halves is sorted (there is only one break, and it can only fall on one side):

  • a[lo] <= a[mid]: the left half a[lo..mid] is sorted. If a[lo] <= x < a[mid], go left, otherwise go right.
  • Otherwise the right half a[mid..hi] is sorted. If a[mid] < x <= a[hi], go right, otherwise go left.

In the sorted half, comparing the two ends tells you whether x is there. This one uses the closed range [lo, hi], because it looks at a[hi] directly.

a (x = 6)151822369120123456↑lo↑hi
1lo, hi = 0, len(a) - 12while lo <= hi:3    mid = (lo + hi) // 24    if a[mid] == x:5        return mid6    if a[lo] <= a[mid]:          # left half sorted7        if a[lo] <= x < a[mid]: hi = mid - 18        else: lo = mid + 19    else:                        # right half sorted10        if a[mid] < x <= a[hi]: lo = mid + 111        else: hi = mid - 112return -1

Finding 6 in the rotated 15 18 22 3 6 9 12: each time, first see which half is sorted, then whether 6 is in that half
main.py
1def search_rotated(a, x):2    lo, hi = 0, len(a) - 13    looks = 04    while lo <= hi:5        mid = (lo + hi) // 26        looks += 17        if a[mid] == x:8            return mid, looks9        if a[lo] <= a[mid]:                # left half sorted10            if a[lo] <= x < a[mid]:11                hi = mid - 112            else:13                lo = mid + 114        else:                              # right half sorted15            if a[mid] < x <= a[hi]:16                lo = mid + 117            else:18                hi = mid - 119    return -1, looks20 21a = [15, 18, 22, 3, 6, 9, 12]22print([search_rotated(a, x)[0] for x in a])23print(search_rotated(a, 6), search_rotated(a, 10), search_rotated(a, 20))24print(search_rotated([3, 1], 1), search_rotated([1], 0), search_rotated([], 5))
Output
[0, 1, 2, 3, 4, 5, 6]
(4, 3) (-1, 3) (-1, 3)
(1, 2) (-1, 1) (-1, 0)

Don't drop the equals sign in a[lo] <= a[mid]: with two left, lo == mid, the left half is just a[mid], and one number is certainly "sorted". Without it, looking for 1 in [3, 1] goes the wrong way. This version needs no repeated numbers; with repeats ([1, 1, 1, 3, 1]), a[lo] == a[mid] can't tell which half is sorted, and you can only shrink with lo += 1, step by step, O(n) in the worst case.

Choose one

The rotated array 6 7 1 2 3 4 5, with lo = 0, hi = 6 and mid = 3. Which half is sure to be sorted?

Exercise 2

The minimum of a rotated array

Complete find_min(a): a is a sorted array without repeats, rotated; return the smallest number in O(log n). Compare a[mid] with a[hi]: a[mid] > a[hi] means the break (the minimum) is right of mid.

It should print
3 0
1 1 7
exercise2.py
1def find_min(a):2    lo, hi = 0, len(a) - 13    # while lo < hi: if a[mid] > a[hi], lo = mid + 1; otherwise hi = mid4    return a[lo]5 6print(find_min([15, 18, 22, 3, 6, 9, 12]), find_min([4, 5, 6, 7, 0, 1, 2]))7print(find_min([1, 2, 3]), find_min([2, 1]), find_min([7]))
Output
Press Run or Ctrl+Enter

Pattern 3: binary search on a condition

One step further: there needn't even be an ordered array, only a condition that is False on a left run and True on a right run, and binary search finds the first True.

The first bad version: versions 1 to n, every version from some point on is bad, is_bad(v) is expensive (build, run the tests), and you want as few calls as possible. is_bad is that False…False True…True condition.

Finding a peak: find a number bigger than both neighbours (outside the two ends counts as minus infinity) in an unsorted array. The condition is "a[mid] > a[mid + 1]": when it holds you are going downhill, and there is surely a peak on the left (mid included); when it doesn't you are going uphill, and the peak is on the right.

a1379842501234567↑lo↑hi
1lo, hi = 0, len(a) - 12while lo < hi:3    mid = (lo + hi) // 24    if a[mid] < a[mid + 1]:5        lo = mid + 16    else:7        hi = mid8return lo

Finding a peak in the unsorted 1 3 7 9 8 4 2 5: downhill go left, uphill go right, 3 looks find 9
main.py
1def peak(a):2    lo, hi = 0, len(a) - 1                 # the answer is an index from 0 to n − 13    while lo < hi:4        mid = (lo + hi) // 2               # mid < hi, so mid + 1 is in range5        if a[mid] < a[mid + 1]:6            lo = mid + 1                   # uphill: the peak is on the right7        else:8            hi = mid                       # downhill: mid itself may be it9    return lo10 11print(peak([1, 3, 7, 9, 8, 4, 2, 5]), peak([1, 2, 3]), peak([3, 2, 1]), peak([5]))12 13def first_bad(n, bad_from):14    calls = 015    def is_bad(v):                         # pretend this step is expensive16        nonlocal calls17        calls += 118        return v >= bad_from19    lo, hi = 1, n                          # the problem promises version n is bad20    while lo < hi:21        mid = (lo + hi) // 222        if is_bad(mid):23            hi = mid24        else:25            lo = mid + 126    return lo, calls27 28print(first_bad(100, 37), first_bad(1_000_000, 765_432), first_bad(1, 1))
Output
3 2 0 0
(37, 7) (765432, 20) (1, 0)

A million versions, 20 calls to is_bad. This is how git bisect finds the commit that brought in a bug: all you answer is "is this version good?".

PatternThe sentence that gives it awayConditionTime
On the answer"the smallest … such that …", "the largest … such that …"ok(answer) monotonicO(one check × log of the range)
Rotated array"a sorted array has been rotated"first see which half is sortedO(log n), worst O(n) with repeats
On a condition"the first …", "find a peak", "bad from some version on"all False on the left, all True on the rightO(log n) checks

In interviews: say the monotonic condition out loud first ("more capacity, fewer days", "is_bad is True from some version on"), then write the code; that sentence is what the interviewer most wants to hear. Use one template for the code: find the first True; when ok(mid), hi = mid, otherwise lo = mid + 1. The bounds must contain the answer: the least capacity's lower bound is max(weights), not 0.

Choose one

Which condition can't be used directly in a "find the first True" binary search?

In two dimensions: a sorted matrix

A matrix increases left to right along each row and top to bottom down each column; find x. Start at the top right: it's the largest in its row and the smallest in its column.

  • Bigger than x: everything below in this column is bigger still, the whole column is out, go left.
  • Smaller than x: everything left in this row is smaller still, the whole row is out, go down.

Each step rules out a row or a column, so an m × n matrix takes at most m + n steps. Starting top left doesn't work: right and down both get bigger, so you can't tell which way to go.

Here is the search for 5 in this 4 × 5 matrix, showing what each step rules out: 15, 11 and 7 are all bigger than 5, each rules out a column, go left; 4 is smaller than 5, it rules out its row, go down; and there is 5.

0123401471115125812192369162231013141724
Finding 5 in the matrix: start at 15 in the top-right corner, go left when it's too big and down when it's too small; 5 boxes and it's found

With a stronger condition, where the first number of each row is bigger than the last number of the row before, you can lay the rows end to end: the matrix becomes one sorted list, item i is m[i // cols][i % cols], and a single binary search does it in O(log(rows × cols)), faster than m + n steps. This stage's exercise is that kind.

Choose one

In the same matrix, starting from the top-right corner, you look for 13. Which numbers do you look at, in order?

Exercise 3

Search a sorted matrix

Each row of the matrix is sorted from small to large, and each row's first number is bigger than the previous row's last. Complete search_matrix(m, x): return (row, column) if found, None if not, in O(log(rows × columns)). Treat it as one sorted list laid flat: entry i is m[i // cols][i % cols].

It should print
(0, 1) (1, 2) (2, 3)
None None None
exercise3.py
1def search_matrix(m, x):2    if not m:3        return None4    rows, cols = len(m), len(m[0])5    lo, hi = 0, rows * cols6    # a half-open binary search; entry mid is m[mid // cols][mid % cols]7    return None8 9m = [[1, 3, 5, 7],10     [10, 11, 16, 20],11     [23, 30, 34, 60]]12print(search_matrix(m, 3), search_matrix(m, 16), search_matrix(m, 60))13print(search_matrix(m, 13), search_matrix(m, 0), search_matrix([], 1))
Output
Press Run or Ctrl+Enter

How you write it at work

All three patterns are one template: find the first number in [lo, hi) for which ok holds. Write it as a function and a problem comes down to writing ok:

main.py
1import math2 3def first_true(lo, hi, ok):           # the first k in [lo, hi) with ok(k) True; hi if there is none4    while lo < hi:5        mid = (lo + hi) // 26        if ok(mid):7            hi = mid8        else:9            lo = mid + 110    return lo11 12n = 2_000_000_00013print(first_true(0, n + 1, lambda k: k * k > n) - 1, math.isqrt(n))14 15a = [58, 60, 60, 72, 85, 85, 85, 91]16print(first_true(0, len(a), lambda i: a[i] >= 85))     # this is bisect_left(a, 85)17 18big = (10**16 + 1) ** 2 - 119print(int(math.sqrt(big)), math.isqrt(big))            # the float square root is off by 2
Output
44721 44721
4
10000000000000002 10000000000000000
  • For an integer square root use math.isqrt(n): exact, right for any n. int(math.sqrt(n)) goes through a float with only 53 bits of precision, and once n is past about 2⁵² it can be a little off; in this stage's example it is off by 2.
  • On a sorted list, use bisect; on an answer or a condition, use a ten-line function like this stage's first_true, which goes wrong less often than writing the while loop again each time.
  • Finding which commit brought in a bug: git bisect start, git bisect bad, git bisect good <commit>, and git hands you a version in the middle to test each time.
Guess the outputA wrong guess is fine

One first_true, three questions. What does this print?

1def first_true(lo, hi, ok):2    while lo < hi:3        mid = (lo + hi) // 24        if ok(mid):5            hi = mid6        else:7            lo = mid + 18    return lo9 10a = [2, 4, 4, 8, 9]11print(first_true(0, len(a), lambda i: a[i] > 4), first_true(0, len(a), lambda i: a[i] > 9), first_true(1, 100, lambda k: k * k >= 50))

Summary

Take-away

Three searching patterns

  • Binary search needs not order but a condition that turns from False to True exactly once
  • On the answer: "the smallest … such that …"; write ok(answer) and find the first True in the answer's range
  • Rotated array: at least one half is sorted; compare the two ends of the sorted half
  • Peak, first bad version: binary search on a condition; when ok(mid), hi = mid, otherwise lo = mid + 1
  • For an integer square root use math.isqrt, not int(math.sqrt(n))
1def first_true(lo, hi, ok):2    while lo < hi:3        mid = (lo + hi) // 24        if ok(mid): hi = mid5        else: lo = mid + 16    return lo

Chapter 6 quick check

Five questions: a binary search bug, bisect's boundaries, one right rotation, binary search on the answer, and finding a peak. Work out what each prints yourself, then pick an option.

Guess the outputA wrong guess is fine

A half-open range, but with hi = mid - 1. Looking for every number, what does it print?

1def find(a, x):2    lo, hi = 0, len(a)3    while lo < hi:4        mid = (lo + hi) // 25        if a[mid] == x:6            return mid7        if a[mid] < x:8            lo = mid + 19        else:10            hi = mid - 111    return -112 13print([find([1, 3, 5, 7, 9], x) for x in [1, 3, 5, 7, 9]])
Guess the outputA wrong guess is fine

Insert one more 2, then find the boundaries. What does it print?

1from bisect import bisect_left, bisect_right, insort2 3a = [1, 2, 2, 2, 5]4insort(a, 2)5print(bisect_left(a, 2), bisect_right(a, 2), bisect_left(a, 3), len(a))
Guess the outputA wrong guess is fine

Rotate 8 right once. It prints the preorder and the new root's right child's left child:

1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def rot_right(t):8    l = t.left9    t.left = l.right10    l.right = t11    return l12 13def pre(node):14    return [node.val] + pre(node.left) + pre(node.right) if node else []15 16t = TreeNode(8, TreeNode(4, TreeNode(2), TreeNode(6)), TreeNode(10))17r = rot_right(t)18print(pre(r), r.right.left.val)
Guess the outputA wrong guess is fine

Find the first number in [0, 100) whose cube is ≥ 100. What does it print?

1lo, hi = 0, 1002rounds = 03while lo < hi:4    rounds += 15    mid = (lo + hi) // 26    if mid ** 3 >= 100:7        hi = mid8    else:9        lo = mid + 110print(lo, rounds)
Guess the outputA wrong guess is fine

Find a peak. a has two peaks: the 2 at index 1 and the 6 at index 5. What does it print?

1a = [1, 2, 1, 3, 5, 6, 4]2lo, hi = 0, len(a) - 13while lo < hi:4    mid = (lo + hi) // 25    if a[mid] < a[mid + 1]:6        lo = mid + 17    else:8        hi = mid9print(lo, a[lo])