#C7476. Find the K-th Element in Merged Sorted Arrays
Find the K-th Element in Merged Sorted Arrays
Find the K-th Element in Merged Sorted Arrays
You are given two sorted arrays and an integer k. Your task is to merge the two arrays into one sorted array and find the element that appears at the k-th position in the merged array. If k is greater than the total number of elements in both arrays, output -1
.
The problem can be formally defined as follows:
Given two sorted arrays \(A\) and \(B\) of lengths \(n\) and \(m\) respectively, find the element at position \(k\) in the sorted array \(C\) which is the merge of \(A\) and \(B\). If \(k > n+m\), then output \(-1\).
Use an efficient merge algorithm based on the two-pointer technique.
inputFormat
The input is given via standard input (stdin
) and consists of four lines:
- The first line contains two space-separated integers \(n\) and \(m\), the sizes of the first and second arrays respectively.
- The second line contains \(n\) space-separated integers representing the elements of the first sorted array.
- The third line contains \(m\) space-separated integers representing the elements of the second sorted array.
- The fourth line contains a single integer \(k\), the position (1-indexed) of the element to retrieve from the merged sorted array.
outputFormat
Output a single integer to standard output (stdout
): the element at the k-th position in the merged sorted array. If no such element exists, output -1
.
5 4
2 3 6 7 9
1 4 8 10
5
6