Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Tuesday, June 6, 2017

Find kth smallest element from two arrays


Idea : is to use merge algorithm to have an array with max range k so that we can save time and get desired result.


import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
 {
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int u=ab.nextInt();
while(u-->0)
{
   int n=ab.nextInt();
   int m=ab.nextInt();
   int k=ab.nextInt();
   int i,j;
   int t=0;
   i=j=0;
   int fin[]=new int[m+n];
   int arr[]=new int[n];
       int arr2[]=new int[m];
   for( i=0;i<n;i++)
   arr[i]=ab.nextInt();
   for( i=0;i<m;i++)
   arr2[i]=ab.nextInt();
   i=0;
   while(i<n && j<m && t<k)
   {
       if(arr[i]<=arr2[j])
       {
           fin[t++]=arr[i++];
       }
       else
       fin[t++]=arr2[j++];
   }
   while(i<n && t<k)
  fin[t++]=arr[i++];
  while(j<m && t<k)
  fin[t++]=arr2[j++];
     System.out.println(fin[k-1]);
}
}
}

0 Comments:

Post a Comment

Stats