Kth Element of Two Sorted Arrays
Kth Element of Two Sorted Arrays is a GFG problem (Medium). You get two arrays a and b, each sorted in ascending order, and a number k. Return the value that would sit at position k (counting from 1) if both arrays were merged into one sorted array.
- Values can repeat, inside one array and across both.
- Each array can hold up to 10⁶ values, and the expected time is logarithmic, so you should not build the merged array.
- 1 <= a.size(), b.size() <= 10⁶
- 0 <= a[i], b[i] <= 10⁸
- 1 <= k <= a.size() + b.size()
- Both arrays are sorted ascending; values may repeat
Intuition
The k smallest values of the merged array are always a prefix of a plus a prefix of b: some i values from a and the other k - i from b. So the only unknown is one number, i.
A guess for i draws a cut through each array. The guess is right when nothing to the left of either cut is bigger than something to the right of the other cut. Only the four values beside the cuts matter.
If the last value taken from a is too big, taking even more from a only makes it worse, so i must shrink. That one-way rule is what lets you binary search i instead of merging, and the k-th value is the larger of the two values just left of the cuts.
Two sorted inputs and a question about a rank in their union (the k-th value, the median) point to searching a split point rather than a value. Once a guess can be judged too far left or too far right, binary search applies.
Approach
Before reading on, merge [2,3,6,7,9] and [1,4,8,10] by hand and stop at the 5th value. Then ask: how many of those 5 came from each array, and could you have guessed that count directly?
Search the shorter array
If a is longer than b, swap them so a is the shorter one. The binary search runs over how many values to take from a, so this keeps the number of probes at O(log min(n, m)).
Limit the range of i
Search i between max(0, k - m) and min(k, n). You cannot take more than n values from a, and j = k - i must not exceed m, the length of b. Every probe in this range is a legal pair of cuts.
Read the four values beside the cuts
For a guess i, set j = k - i. Read a[i-1] and a[i], the values on either side of the cut in a, and b[j-1] and b[j] in b. A side with nothing there counts as −∞ on the left and +∞ on the right, so empty prefixes need no special code.
Move the cut or stop
If a[i-1] <= b[j] and b[j-1] <= a[i], the cut is right. If a[i-1] > b[j], too much was taken from a, so search lower. Otherwise too little was taken from a, so search higher.
Why the answer is the larger left value
With a correct cut, the left sides hold exactly the k smallest values. The largest of them is the k-th, and it must be a[i-1] or b[j-1], because each array is sorted. So return max(a[i-1], b[j-1]).
Code in Python, C++ and Java
Common pitfalls
Searching i from 0 to n
lo, hi = 0, len(a)
lo, hi = max(0, k - m), min(k, n)
Small guesses for i make j = k - i larger than b. With a = [3], b = [1, 2] and k = 3, the first probe is i = 0, so j = 3 and b[j - 1] reads past the end of b.
Strict comparisons at the cut
if a_left < b_right and b_left < a_right:
if a_left <= b_right and b_left <= a_right:
Equal values on both sides of a cut are allowed. With a = [1, 1], b = [1, 1] and k = 2, no cut passes the strict test, the loop runs out, and the function returns -1 instead of 1.
Reading k as a 0-based index
return merged[k]
return merged[k - 1]
Position k counts from 1. In the merge version this returns the value one place too far, and for k = n + m it reads past the end.
Edge cases
a = [1, 2, 3], b = [4, 5, 6], k = 4The cut takes all of a (i = 3) and one value of b. The right side of a is empty, so it counts as +∞ and the check passes; the answer is 4.
k = 1 or k = n + mThe range for i is still valid at both ends. For k = 1 one side takes nothing and its left value is −∞, so the answer is the smaller first value.
Complexity
i, which has at most min(n, m) + 1 values. A probe reads four values and does two comparisons. Only a few numbers are stored, and the swap is a recursive call that happens at most once.Kth Element of Two Sorted Arrays FAQ
How is this related to Median of Two Sorted Arrays?
The median is this problem with k fixed at the middle of the merged length (and the two middle values averaged when the length is even). The same cut search solves both. See Median of Two Sorted Arrays for that version.
Is a two-pointer merge good enough?
It is correct and simple: walk both arrays like the merge step of merge sort and stop after k picks. That costs O(k), up to 2·10⁶ steps here, which usually passes but does not meet the expected logarithmic time.
Why can the answer not be a value right of the cut?
Take a = [2, 3, 6, 7, 9], b = [1, 4, 8, 10], k = 5. The correct cut takes [1, 4] from b and [2, 3, 6] from a. Everything right of the cuts (7, 9, 8, 10) is at least 6, and there are exactly 5 values on the left, so 6, the largest left value, is 5th.