Kth Element of Two Sorted Arrays
Two sorted arrays; return the k-th smallest of their union in logarithmic time.
Open on GeeksforGeeks ↗Intuition
Take exactly k elements as a prefix of A plus a prefix of B. The split is valid when nothing left of either cut exceeds anything right of the other cut. Binary search how many of the k come from A — validity is monotone in that count.
Median-of-two-sorted-arrays generalised: binary search the partition so that exactly k elements fall on the left. The bounds max(0, k - m) and min(k, n) matter — they keep j = k - i inside the second array. Searching a partition point rather than a value is the transferable move.
Approach
Partition, don't merge
Choose i from A and k−i from B. The k-th smallest is max(A[i−1], B[k−i−1]) for the valid split — no O(k) walk.
Validity check
Split is valid iff A[i−1] ≤ B[k−i] and B[k−i−1] ≤ A[i] (missing neighbours = ±∞). If A's last taken is too big, take fewer from A.
Search on the smaller array
Binary search i in [max(0,k−m), min(k,n)] on the shorter array → O(log min(n,m,k)).
Solution & live demo
Common pitfalls
Merging until the k-th element
merged = sorted(a + b) return merged[k - 1]
i = (lo + hi) // 2 j = k - i
O((n + m) log(n + m)) to read one element. Binary searching the split touches only the four values straddling it, giving O(log min(n, m)).
Using 0 and n as the search bounds
lo, hi = 0, n
lo, hi = max(0, k - m), min(k, n)
j = k - i must be a legal index into b. If k exceeds m, taking too few from a pushes j past the end of b; the tightened bounds make every probe valid without extra guards.
Binary searching the longer array
# no swap n, m = len(a), len(b)
if len(a) > len(b): a, b = b, a
Complexity is O(log min(n, m)) only when you search the shorter side, and the bound arithmetic assumes it. Swapping up front costs nothing and keeps both properties.
Edge cases
Lower bound max(0, k−m) forces enough elements from the other array.
Valid split takes i=2, j=0; sentinels ±∞ make the checks pass.