Problem :Given two sorted arrays, merge them to form a new array of unique items.
If an item is present in both arrays, it should be part of the resulting array if and only if it appears in both arrays the same number of times.
e.g.:
a = [1, 3, 40, 40, 50, 60, 60, 60]
andb = [2, 40, 40, 50, 50, 65]
, should return[1, 2, 3, 40, 60, 65]
a = [2,2,2,2,40,40,50]
andb = [40,40,60]
should return[2,40,50,60]
a = [5,5]
andb = [5,5,5]
should return[]
My problem is that my function is not efficient enough (runtime takes too long), is it possible to may it more efficient? Possibly O(a+b)
function mergeArrays(a, b) {
function countInArray(array, array2, what) {
var count = 0;
var count2 = 0;
for (var i = 0; i < array2.length; i++) {
if (array2[i] === what) {
count2++;
}
}
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count === count2;
}
var arr = []
for (x = 0; x < b.length; x++) {
if (!a.includes(b[x]) && !arr.includes(b[x]))
arr.push(b[x])
}
for (i = 0; i < a.length; i++) {
if (countInArray(a, b, a[i]) && !arr.includes(a[i])) {
arr.push(a[i])
} else {
if (!arr.includes(a[i]) && !b.includes(a[i]))
arr.push(a[i])
}
}
console.log(arr)
return arr.sort(function(a, b) {
return a - b
});
}