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.
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
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.