Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Median of two sorted arrays

Hard · Target 30 minutes · Binary search · Type asked atGoogleGoldman SachsApple

Given two sorted arrays a and b (either may be empty, not both), return the median of all their elements together: the middle value if the total count is odd, the mean of the two middle values if it is even. Use O(log(min(m, n))) time.

Examples

InputOutputWhy
a = [1, 3], b = [2]2.0
a = [1, 2], b = [3, 4]2.5Merged: 1, 2, 3, 4; (2 + 3) / 2.
a = [], b = [1]1.0

Constraints

  • 0 ≤ m, n ≤ 1000, m + n ≥ 1
  • −10⁶ ≤ values ≤ 10⁶
  • Return a floating-point number

Hints

Hint 1

The median splits the merged list into a lower half and an upper half. Any such split takes some prefix of a and some prefix of b.

Hint 2

If the lower half has L = ⌈(m + n)/2⌉ elements and takes i of them from a, it takes L − i from b. Only i is free.

Hint 3

The split is right when a[i − 1] ≤ b[L − i] and b[L − i − 1] ≤ a[i]. If a[i − 1] is too big, take fewer from a; if b[L − i − 1] is too big, take more. Binary search i over the shorter array.

Where people lose marks

  • Searching over the longer array: j can then go negative or past n.
  • Forgetting the sentinels when i or j is 0 or the full length.
  • Integer division in the even case: (3 + 4) / 2 must be 3.5, not 3.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.