Find the uncommon elements from common elements of an array.

In the below scenario, you are given with two array. mention the size of first array and then elements separated by space and similarly for the second array size and elements. Now need to find the uncommon elements between the common elements of array.

import java.util.*;
public class HackerRank {
public static String uncommonBetweenCommon(int[] input1,int[] input2)
{
String output=null;
int count=0;
List<Integer> value=new ArrayList<Integer>();
int [] combined=new int [input1.length+input2.length];
System.arraycopy(input1, 0, combined, 0, input1.length); //copying first array
System.arraycopy(input2, 0, combined, input1.length,input2.length); //copying second array
for(int i=0;i<combined.length;i++){
int x=combined[i];
for(int j=0;j<combined.length;j++){
int y=combined[j];
if(x==y){
count++;
}
}
if(count<2){
value.add(x);
}
count=0;
}
Integer[] unique=value.toArray(new Integer[value.size()]); //converting List<Integer> to Integer []
output=String.valueOf(unique[0]);
for(int k=1;k<unique.length;k++){
output+="$"+unique[k];
}
return output;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String output;
int ip1_size = 0;
ip1_size = Integer.parseInt(in.nextLine().trim());
int[] ip1 = new int[ip1_size];
int ip1_item;
for(int ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
ip1_item = Integer.parseInt(in.nextLine().trim());
ip1[ip1_i] = ip1_item;
}
int ip2_size = 0;
ip2_size = Integer.parseInt(in.nextLine().trim());
int[] ip2 = new int[ip2_size];
int ip2_item;
for(int ip2_i = 0; ip2_i < ip2_size; ip2_i++) {
ip2_item = Integer.parseInt(in.nextLine().trim());
ip2[ip2_i] = ip2_item;
}
output = uncommonBetweenCommon(ip1,ip2);
System.out.println(String.valueOf(output));
in.close();
}
}



Output:
3                                        //first array size
1                                        //first array elements
2                                                ....
3                                                 ...
4                                          //second array size
3                                           //second array elements
4                                                            ..
5                                                            ..
6                                                            ..
1$2$4$5$6                           //required output

Comments

Popular posts from this blog

Reasoning-Number Series

Profit and Loss

Reasoning-Letter Series