Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Median of two sorted arrays in O(log(min(m, n))) by binary searching the partition of the shorter array.

Problem: Median of two sorted arrays in O(log(min(m, n))) by binary searching the partition of the shorter array.
def median(a, b):
    if len(a) > len(b): a, b = b, a
    m, n = len(a), len(b); lo, hi = 0, m
    while lo <= hi:
        i = (lo + hi) // 2; j = (m + n + 1) // 2 - i
        L1 = a[i-1] if i else float('-inf'); R1 = a[i] if i < m else float('inf')
        L2 = b[j-1] if j else float('-inf'); R2 = b[j] if j < n else float('inf')
        if L1 <= R2 and L2 <= R1:
            if (m + n) % 2: return max(L1, L2)
            return (max(L1, L2) + min(R1, R2)) / 2
        if L1 > R2: hi = i - 1
        else: lo = i + 1
print(median([1, 3, 8, 9, 15], [7, 11, 18, 19, 21, 25]))
What is printed?
  1. A. 9
  2. B. 10.0
  3. C. 11
  4. D. 15

Correct answer: C. 11

There are 11 values, so the median is the 6th smallest: 1, 3, 7, 8, 9, 11, … gives 11. The search settles on i = 4, j = 2: the left side {1, 3, 8, 9} ∪ {7, 11} has every value ≤ the right side {15} ∪ {18, …}, and with an odd total the median is max(9, 11) = 11.

More Coding Interview Problems questions

Exams that ask this topic