In an interview I was asked the following question. I am given two arrays, both of them are sorted.
BUT
Array 1 will have few -1\'s and Array 2 will have to
function merger(a1, a2) {
var i = 0;
var j = 0;
while (i < a1.length && j < a2.length) {
if (a1[i] > a2[j]) {
// Swap values
var temp = a2[j];
a2[j] = a1[i];
a1[i] = temp;
i++;
} else if (a1[i] !== -1 && a1[i] <= a2[j]) {
i++;
} else {
var temp = a2[j];
a2[j] = a1[i];
a1[i] = temp;
i++;
j++;
}
}
return a1;
}
var arrayOne = [3, 5, -1, 11, 15, -1, 23, 34, -1, 42];
var arrayTwo = [6, 19, 38];
console.log(merger(arrayOne, arrayTwo))
With certain pre-conditions (no other numbers with <0, a1 should be smaller than a2 etc - which could all be handled) this should solve the problem in JS.