CodeArchon

hardBinary SearchAmazonGoogleApple

Dual-Sorted Median

Two independently sorted sensor logs are to be merged conceptually. Report the median of the combined readings in O(log(min(m,n))).

Given two sorted integer arrays `a` and `b`, return the median of their union.

Choose approach

1
0
3
1
2
2
1/5
Narrationstep 1 of 5

Shorter array first (1 vs 2). Binary-search how many of the smaller array go into the left half.

1def dual_sorted_median(a: list[int], b: list[int]) -> float:
2 if len(a) > len(b):
3 a, b = b, a
4 m, n = len(a), len(b)
5 lo, hi = 0, m
6 while lo <= hi:
7 i = (lo + hi) // 2
8 j = (m + n + 1) // 2 - i
9 a_left = float('-inf') if i == 0 else a[i - 1]
10 a_right = float('inf') if i == m else a[i]
11 b_left = float('-inf') if j == 0 else b[j - 1]
12 b_right = float('inf') if j == n else b[j]
13 if a_left <= b_right and b_left <= a_right:
14 if (m + n) % 2:
15 return max(a_left, b_left)
16 return (max(a_left, b_left) + min(a_right, b_right)) / 2
17 if a_left > b_right:
18 hi = i - 1
19 else:
20 lo = i + 1
21 return 0
Variables
m=1
n=2
lo=0
hi=1

How to think about it

  1. Merged array has median = middle element (odd) or avg of middle two (even).
  2. Pick i elements from the shorter array; j = ⌈(m+n)/2⌉ − i from the other.
  3. Partition is valid iff aLeft ≤ bRight AND bLeft ≤ aRight.
  4. If aLeft > bRight, move i left; if bLeft > aRight, move i right.
  5. Binary-search over i in [0..m] → O(log m).

Edge cases to catch in interview

  • One empty — median = middle of the other.
  • Different sizes — the swap-at-top guarantees we binary-search the smaller.
  • Integer overflow in Java: use careful midpoint.

Examples

Example 12.0
{"a":[1,3],"b":[2],"values":[1,3,2]}
Example 22.5
{"a":[1,2],"b":[3,4],"values":[1,2,3,4]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed