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

Problem: Find the median of two sorted arrays of sizes m and n (up to 10⁶ each) in better than linear time. What is the optimal complexity?

  1. A. O(m + n) – merging is required
  2. B. O(log m · log n)
  3. C. O((m + n) log(m + n)) – sort the union
  4. D. O(log(min(m, n))) – binary search the partition of the smaller array

Correct answer: D. O(log(min(m, n))) – binary search the partition of the smaller array

Choose i elements from the smaller array and (m + n + 1)/2 − i from the other so that all left parts ≤ all right parts; this condition is monotonic in i, so binary search on the smaller array suffices. Merging is O(m + n).

More Coding Interview Problems questions

Exams that ask this topic