You are given two arrays A and B, each already sorted in non-decreasing order, and a 1-indexed position k. Consider merging A and B into one non-decreasing sequence (keeping duplicates). Output the value at position k of that merged sequence — that is, the k-th smallest value of the combined multiset.
You do not need to materialize the merged array: walk both arrays with two pointers, always taking the smaller front element, and stop after k elements have been taken.
Line 1: three integers n, m, k separated by spaces — the length of A, the length of B, and the 1-indexed position.
Line 2: n space-separated integers, array A in non-decreasing order (empty when n == 0).
Line 3: m space-separated integers, array B in non-decreasing order (empty when m == 0).
A single integer: the k-th smallest value of the merged multiset.
k is a valid position)A and B are guaranteed to be sorted in non-decreasing order.Example 1
Input
3 3 4 1 3 5 2 4 6
Expected
4
Explanation
Merging [1,3,5] and [2,4,6] gives [1,2,3,4,5,6]. The 4th smallest value is 4.
Example 2
Input
2 0 2 7 9
Expected
9
Explanation
Array B is empty, so the merged sequence is just [7,9]. The 2nd smallest value is 9.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →