K-th element of two sorted Arrays
Problem
Given two sorted arrays arr1 and arr2 of size N and M respectively and an element K. The task is to find the element that would be at the k’th position of the final sorted array.Solution Approach
Merge 2 array approach.
Expected Time complexity:
Click - to see solution code
- C++
class Solution {
public:
int kthElement(int arr1[], int arr2[], int n, int m, int k) {
int ele;
int i = 0, j = 0;
while (i < n && j < m) {
if (arr1[i] <= arr2[j]) {
ele = arr1[i];
i++;
if (i + j == k) return ele;
} else {
ele = arr2[j];
j++;
if (i + j == k) return ele;
}
}
while (i < n) {
ele = arr1[i++];
if (i + j == k) return ele;
}
while (j < m) {
ele = arr2[j++];
if (i + j == k) return ele;
}
return -1;
}
};