Python coding

Median across two sorted lists

Given two lists a and b, each sorted in non-decreasing order (values may repeat), return the median of all their values taken together: the middle value when the total count is odd, or the average of the two middle values when it is even. One of the lists may be empty, but not both.

Aim for O(log(min(m, n))): merging the two lists is O(m + n).

  • median_of_two([1,4,9], [2,6]) → 4
  • median_of_two([1,3], [2,4]) → 2.5
  • median_of_two([], [2,4,7]) → 4
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

You do not need the merged list, only the cut that leaves half of all the values on the left. If a gives i values to that half, b must give half − i.

Hint 2

The cut is right when a[i-1] <= b[j] and b[j-1] <= a[i]. If a[i-1] > b[j] you took too many from a: go left; otherwise go right. Binary search i.

Hint 3

Search the shorter list so j stays in range, use −∞/+∞ when a side of the cut is empty, and average the two middle values when the total is even.

Solution and why it works
pythonO(log(min(m, n))), m = len(a), n = len(b) · O(1)
def median_of_two(a: list[int], b: list[int]) -> float:
    if len(a) > len(b):
        a, b = b, a                              # binary search the shorter list
    total = len(a) + len(b)
    half = (total + 1) // 2                      # how many values go left of the cut
    lo, hi = 0, len(a)
    while True:
        i = (lo + hi) // 2                       # values taken from a
        j = half - i                             # values taken from b
        a_left = a[i - 1] if i > 0 else float("-inf")
        a_right = a[i] if i < len(a) else float("inf")
        b_left = b[j - 1] if j > 0 else float("-inf")
        b_right = b[j] if j < len(b) else float("inf")
        if a_left > b_right:
            hi = i - 1                           # took too many from a
        elif b_left > a_right:
            lo = i + 1                           # took too few from a
        else:
            left_max = max(a_left, b_left)
            if total % 2:
                return float(left_max)
            return (left_max + min(a_right, b_right)) / 2

The median splits the merged values into a left and a right part, with everything on the left ≤ everything on the right. Taking i values from a forces j = half − i from b, so i is the only unknown, and the cut is right when a[i−1] <= b[j] and b[j−1] <= a[i]. If the first fails, i is too big; if the second fails, too small: binary search. Search the shorter list so j never goes negative, and treat a missing neighbor as ±infinity.

Related lab: Loops in motion