Python 3D Academyবাংলা

Turned-round lists and sorted grids

🌍 In real life. The departure board at the bus terminal starts from now, 6 pm: 18:00, 20:00, 22:00, 23:00, then the first buses of tomorrow, 05:00, 06:00, 08:00. The times go up, drop once, and go up again: a sorted list turned round. And in the cinema hall, seats are numbered row after row, 1 to 10 in row A, 11 to 20 in row B, and so on: a grid that is sorted if you read it row by row.

Neither is a plain sorted list, but both are sorted enough for binary search, once you see how.

A turned-round list: the idea in one sentence. Cut a turned-round sorted list at any middle and at least one half is still in order (the single drop is in the other half); check whether the target lies within that ordered half's first and last values, and keep the half where it can be.

Its words: a rotated sorted list is a sorted list cut in two and the parts swapped, like [4, 5, 6, 7, 0, 1, 2]; the values here are all different.

Step by step:

  1. lo, hi = 0, len(a) - 1; while lo <= hi: mid = (lo + hi) // 2; found? return mid
  2. a[lo] <= a[mid]: the left half a[lo..mid] is in order. If a[lo] <= target < a[mid], search left (hi = mid - 1), else right (lo = mid + 1)
  3. otherwise the right half a[mid..hi] is in order. If a[mid] < target <= a[hi], search right, else left
  4. return -1 when lo > hi

The purple bar marks the half that is in order:

A sorted grid: the idea in one sentence. When every row goes up and starts above where the row before ends, reading row after row gives one sorted list, so binary search positions 0 to rows × cols − 1, and turn each position into a row and a column with r, c = divmod(i, cols).

In a grid with 4 columns, position 6 is row 1, column 2 (6 = 1 × 4 + 2). No list is built: each look works out where the middle is.

Why it is correct.

  • Turned round: the list drops only once, so the drop lies in at most one half, and the other half is a plain sorted run. For a sorted run, "is the target between its first and last value?" decides exactly whether it can be there. So each look throws away a half that cannot hold the target, and the invariant of Lesson 43.1 still holds.
  • The grid: reading row by row really is sorted (each row starts above the last row's end), and divmod turns positions into cells one to one, so this is Lesson 43.1's search on a list you never had to build.

What it costs. Both halve what is left at every look: O(log n) for a turned-round list, and O(log(rows × cols)) for a grid. A grid of 30 rows and 40 columns (1200 seats) needs at most 11 looks; searching each row with binary search would need about 30 × 6, and checking every seat 1200.

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]:                  # the left half is in order
            if a[lo] <= target < a[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:                                # the right half is in order
            if a[mid] < target <= a[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1

def search_matrix(m, target):
    rows, cols = len(m), len(m[0])
    lo, hi = 0, rows * cols - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        r, c = divmod(mid, cols)             # position mid as row, column
        if m[r][c] == target:
            return True
        if m[r][c] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return False

board = [18, 20, 22, 23, 5, 6, 8]
print(search_rotated(board, 6), search_rotated(board, 21))
grid = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
print(search_matrix(grid, 16), search_matrix(grid, 13))

Mistakes and edge cases.

  • a[lo] < a[mid] instead of <=: when lo == mid (two items left) the left "half" is one item, which is in order; with < the search looks on the wrong side
  • open and closed ends: a[lo] <= target < a[mid] is "from a[lo] up to just before a[mid]"; a[mid] was already checked
  • repeated values: with duplicates, a[lo] == a[mid] doesn't tell which half is in order, and the search can go wrong; this lesson's lists have different values
  • the grid: divmod(mid, cols), not rows; and an empty grid has no m[0], so check it first if it can happen

Quiz

  1. What does this print?

    for i in [0, 5, 11]:
        print(divmod(i, 4), end=" ")
  2. Why is at least one half of a turned-round sorted list always in order?

    • The values drop only once, and that drop can be in only one of the halves
    • Because the middle is always the smallest value
    • It isn't: sometimes neither half is in order
  3. Searching [5, 7, 9, 1, 3] for 3: lo = 0, hi = 4, mid = 2 holds 9. Where do you look next?

    • The right half: the left half 5..9 is in order and 3 is not in it
    • The left half: 3 is smaller than 9
    • Nowhere: 3 is not there
  4. search_matrix goes wrong on a grid with 2 rows and 5 columns, and can even crash. Which line is wrong?

    def search_matrix(m, target):
        rows, cols = len(m), len(m[0])
        lo, hi = 0, rows * cols - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            r, c = divmod(mid, rows)
            if m[r][c] == target:
                return True
            if m[r][c] < target:
                lo = mid + 1
            else:
                hi = mid - 1
        return False
  5. What does searching a sorted grid of rows × cols cost this way?

    • O(log(rows × cols))
    • O(rows × cols)
    • O(rows × log cols)

Coding tasks

  1. Write search_rotated(nums, target) for a sorted list of different numbers that has been turned round: the position of target, or -1. Halve the search each look: on 1000 items it may compare at most 80 times.

  2. Write search_matrix(matrix, target): True if target is in a grid where every row goes up and starts above where the row before ends, else False. Use one binary search over all positions: on a 30 × 40 grid it may compare at most 40 times.