K-th element of two sorted Arrays | Practice | GeeksforGeeks

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.
 
Example 1:
Input:
arr1[] = {2, 3, 6, 7, 9}
arr2[] = {1, 4, 8, 10}
k = 5
Output:
6
Explanation:
The final sorted array would be -
1, 2, 3, 4, 6, 7, 8, 9, 10
The 5th element of this array is 6.

Input:
arr1[] = {100, 112, 256, 349, 770}
arr2[] = {72, 86, 113, 119, 265, 445, 892}
k = 7
Output:
256
Explanation:
Final sorted array is - 72, 86, 100, 112,
113, 119, 256, 265, 349, 445, 770, 892
7th element of this array is 256.

Your Task:  
You don't need to read input or print anything. Your task is to complete the function kthElement() which takes the arrays arr1[], arr2[], its size N and M respectively and an integer K as inputs and returns the element at the Kth position.

Expected Time Complexity: O(Log(N) + Log(M))
Expected Auxiliary Space: O(Log (N))

Constraints:
1 <= N, M <= 106
1 <= arr1i, arr2i < INT_MAX
1 <= K <= N+M
0
yuvrajranabtcse203 days ago
c++ soln
int ans=0,i=0,j=0,count=0,check=-1,last=0;      while((i<n)&&(j<m)){           if(arr1[i]<=arr2[j]){               last=arr1[i];               i++;               count++;           }           else{               last=arr2[j];               j++;               count++;           }           if(count==k)return last;       }       if(i==n)return arr2[j+k-count-1];       else return arr1[i+k-count-1];   }
0
nischithtn
This comment was deleted.
-2
nischithtn6 days ago
int arr3[]=new int[m+n];     System.arraycopy(arr1,0,arr3,0,n);     System.arraycopy(arr2,0,arr3,n,m);     Arrays.sort(arr3);     return arr3[k-1];
0
mridulkapoor1234561 week ago
class Solution{
    public:
    // Two Pointer APPROACH
    /*int kthElement(int arr1[], int arr2[], int n, int m, int k)
    {
        int ptr1=0,ptr2=0;
        int i=1,j=1;
        int ans=0;
        while(k>0){
            if((arr1[ptr1]<arr2[ptr2] && ptr1<n) || ptr2>=m){
                ans=arr1[ptr1];
                k--;
                ptr1++;
            }
            else{
                ans=arr2[ptr2];
                k--;
                ptr2++;
            }
        }
        return ans;
    }*/
    
    //OPTIMAL BINARY SEARCH APPROACH
    int kthElement(int arr1[], int arr2[], int n, int m, int k)
    {
        if(n>m){
            return kthElement(arr2,arr1,m,n,k);
        }
        int lo=max(0,k-m);
        int hi=min(n,k);
        while(lo<=hi){
            int cut1=(lo+hi)>>1;
            int cut2=k-cut1;
            
            int l1 = cut1 == 0 ? INT_MIN : arr1[cut1-1];
            int l2 = cut2 == 0 ? INT_MIN : arr2[cut2-1];
            int r1 = cut1 == n ? INT_MAX : arr1[cut1];
            int r2 = cut2 == m ? INT_MAX : arr2[cut2];
            
            if(l1<=r2 and l2<=r1){
                return max(l1,l2);
            }
            else if(l1>r2)
                hi=cut1-1;
            else
                lo=cut1+1;
        }
        return 1;
    }
};
0
gcharansaicis191 week ago
int kthElement(int arr1[], int arr2[], int n, int m, int k)   {       priority_queue<int> pq;       for(int i=0;i<n;i++)       {           pq.push(arr1[i]);       }       for(int i=0;i<m;i++)       {           pq.push(arr2[i]);       }       for(int j=0;j<n+m-k;j++)       {           pq.pop();       }       return pq.top();          }
+1
deskhell1 week ago
This is a binary search problem where at each point we are required to select a total of k elements from both the array. If the taken elements are correct then output the results:
int kthElement(int arr1[], int arr2[], int n, int m, int k)
    {
        if(n > m){
            swap(arr1, arr2);
            swap(n, m);
        }
        if(n + m < k)return -1;
        
        int low = 0, high = min(k, n);
        while(low <= high){
            int cut1 = (low + high) / 2;
            int cut2 = k - cut1;
            if(cut2 > m){
                low = cut1 + 1;
                continue;
            }
            //cout << cut1 << " " << cut2 << "\n";
            int l1 = cut1 == 0 ? INT_MIN : arr1[cut1 - 1];
            int r1 = cut1 == n ? INT_MAX : arr1[cut1];
            
            int l2 = cut2 == 0 ? INT_MIN : arr2[cut2 - 1];
            int r2 = cut2 == m ? INT_MAX : arr2[cut2];
   
            if(l1 <= r2 and l2 <= r1){
                return max(l1, l2);
            }
            
            else if(l1 > r2)high = cut1 - 1;
            else low = cut1 + 1;
        }
        return 0;
    }
0
rajdeepchakraborty7282 weeks ago
A Simple Python Solution
Time Complexity - O(log (smaller array))
Aux Space - O(Constant)
 
def kthElement(self,  arr1, arr2, n, m, k):              # If Arr1 is the greater array we swap the arrays       # Always binary search should be performed on the lesser size array       # arr1 always remains first array and arr2 second array       if (n > m):           arr1,arr2=arr2,arr1;           n,m=m,n;              #Declare two variables to hold the min or max integer values for corner cases           vIntMax=sys.maxsize;       vIntMin=0-vIntMax;              #If Element to be find (k) is greater than arr2 means longest array then atleast k-m elements are required        #from arr1 to perform binary search. So bare minimum k- (length of array2) would be required from 1st array if k>n        low=max(0,k-m);              #High index will be minimum of k or length of arr1       high=min(k,n);              while (low <= high):                      #Calculate mid of array1 from low and high           mid1=(low+high)//2;                      #Calculate mid of array2 for rest of the elements of k except already already considered from array1           mid2=(k-mid1);                      #If Mid Element of Array1 are any corner elements then l1 or r1 map it to min or max of int           if (mid1 == 0 or mid1 == n):               if (mid1 == 0):                   l1=vIntMin;                   r1=arr1[mid1];                              elif (mid1 == n):                   l1=arr1[mid1-1];                   r1=vIntMax;                              else:               l1=arr1[mid1-1];               r1=arr1[mid1];                      #If Mid Element of Array2 are any corner elements then l2 or r2 map it to min or max of int           if (mid2 == 0 or mid2 == m):                               if (mid2 == 0):                   l2=vIntMin;                   r2=arr2[mid2];                              if (mid2 == m):                   l2=arr2[mid2-1];                   r2=vIntMax;                      else:               l2=arr2[mid2-1];               r2=arr2[mid2];                      #Check Cross array last highest and initial lowest positions to ensure            #all left elements combined of both arrays are lesser than all right elements combined of both arrays           if (l1 <= r2 and l2 <= r1):               return max(l1,l2);                      #l2 of array2 is greater than r1 of array1 means array1 more elements to be sent to left and similarly           #same elements from array2 to be sent at right side. So low index to be increased           elif (l2 > r1):               low=mid1+1;                          else:               high=mid1-1;                      return -1
0
hk63017359392 weeks ago
JAVA SOLUTION..............
public long kthElement( int arr1[], int arr2[], int n, int m, int k) {       int arr[] = new int[n+m];       int i=0,j=0,k1=0;       Arrays.sort(arr1);       Arrays.sort(arr2);       while(i<n && j<m){           if(arr1[i]<arr2[j]){               arr[k1++]=arr1[i];               i++;           }           else{               arr[k1++]=arr2[j];               j++;           }       }       if(i==n)       while(j<m){           arr[k1++]=arr2[j++];       }       if(j==m)       while(i<n){           arr[k1++]=arr1[i++];       }              Long o1 = new Long(arr[k-1]);       return o1;   }
-1
pruthvibelgaonkar4692 weeks ago
USING VECTOR CPP
 
 int kthElement(int a1[], int a2[], int n, int m, int k)   {       vector<int>v;       for(int i=0;i<n;i++)       {           v.push_back(a1[i]);       }       for(int i=0;i<m;i++)       {           v.push_back(a2[i]);       }       sort(v.begin(),v.end());       int x;       for(int i=0;i<v.size();i++)       {           x=v[k-1];       }       return x;   }
-1
aashaykaurav2 weeks ago
def kthElement(self,  arr1, arr2, n, m, k):       Arr = []       arr1.sort()       arr2.sort()       i, j = 0, 0       while i < n and j < m:           if arr1[i] <= arr2[j]:               Arr.append(arr1[i])               i += 1           else:               Arr.append(arr2[j])               j += 1       if i == n:           while j < m:               Arr.append(arr2[j])               j += 1                      if j == m:           while i < n:               Arr.append(arr1[i])               i += 1                      return Arr[k-1]
 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.