Median of Two Sorted Arrays
Return the median of two sorted arrays in O(log(min(n,m))).
Open on LeetCode ↗Intuition
The median splits the union into equal halves. So find a cut of A and a cut of B whose left parts together hold half the elements, with everything left of the cuts ≤ everything right. Binary search where to cut A — B's cut is then forced.
Approach
Cut both arrays
Cut A at i and B at j with i + j = (n+m+1)//2. Left halves combined = half the union (the +1 favours the left for odd totals).
Valid cut condition
Need A[i−1] ≤ B[j] and B[j−1] ≤ A[i] (±∞ sentinels at the edges). If A[i−1] > B[j], the cut in A is too far right — move left.
Read off the median
Odd total: max of the left halves. Even: average of max(left) and min(right). Search only the shorter array for O(log min(n,m)).
Solution & live demo
Edge cases
Cut takes 0 from it; sentinels handle every comparison — median of the other array.
Search pushes i to n; sentinel +∞ on A's right keeps checks valid.