In an interview it was asked to find non- common elements between two string arrays.
Eg: String a[]={"a","b","c","d"};
String b[]={"b","c"};
O/p should be a,d
I have answered to the question that in Java Set is implemented using HashTable. The code with Set is much simpler:
String[] a = {"a","b","c","d"};
String[] b = {"b", "c"};
Set<String> set = new HashSet<>(a.length);
for(String s : a){
set.add(s);
}
for(String s : b){
set.remove(s);
}
return set;
now my query is that is there any other better approach to achieve this
I would handle this in three steps:
a
but not b
b
but not a
So for example:
Set<String> aSet = new HashSet<>(Arrays.asList(a));
Set<String> bSet = new HashSet<>(Arrays.asList(b));
Set<String> aNotB = new HashSet<>(aSet);
aNotB.removeAll(bSet);
Set<String> bNotA = new HashSet<>(bSet);
bNotA.removeAll(aSet);
Set<String> onlyOne = new HashSet<>(aNotB);
onlyOne.addAll(bNotA);
(The stream code in Java 8 may well make this simpler too...)
The code could be made shorter if you don't mind modifying aSet
and bSet
, but I find this version easier to read.
See more on this question at Stackoverflow