Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the k-th smallest element of the union of two sorted arrays (k is 1-based) in O(log(m + n)).

Problem: Return the k-th smallest element of the union of two sorted arrays (k is 1-based) in O(log(m + n)).
def kth(a, b, k):
    if not a: return b[k - 1]
    if not b: return a[k - 1]
    if k == 1: return min(a[0], b[0])
    i = min(len(a), k // 2); j = min(len(b), k // 2)
    if a[i - 1] < b[j - 1]:
        return kth(a[i:], b, k - i)
    return kth(a, b[j:], k - j)
x, y = [1, 4, 7, 10], [2, 3, 8]
print(kth(x, y, 4), kth(x, y, 6), (kth(x, y, 3) + kth(x, y, 4)) / 2)
What is printed?
  1. A. 4 7 3.5
  2. B. 4 8 3.5
  3. C. 3 8 3.5
  4. D. 4 8 4.0

Correct answer: B. 4 8 3.5

Discard k/2 elements from the array whose k/2-th element is smaller – they cannot contain the k-th. Merged: 1, 2, 3, 4, 7, 8, 10 → 4th = 4, 6th = 8, and the average of the 3rd and 4th is (3 + 4)/2 = 3.5. (With 7 elements the true median is just the 4th, 4 – the last expression is the even-length formula.) Each step removes about k/2: O(log k).

More Coding Interview Problems questions

Exams that ask this topic