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
03
12
21/5
Narrationstep 1 of 5
Shorter array first (1 vs 2). Binary-search how many of the smaller array go into the left half.
Variables
m=1
n=2
lo=0
hi=1
How to think about it
- Merged array has median = middle element (odd) or avg of middle two (even).
- Pick i elements from the shorter array; j = ⌈(m+n)/2⌉ − i from the other.
- Partition is valid iff aLeft ≤ bRight AND bLeft ≤ aRight.
- If aLeft > bRight, move i left; if bLeft > aRight, move i right.
- 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 1
2.0{"a":[1,3],"b":[2],"values":[1,3,2]}
Example 2
2.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