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
You can try following approach:
arrayTwo
and keep it in a variable say val
.arrayOne
and check if current value is greater than val
, push it in array and decrement value of i
by 1 to check next value as well with current element.0
, ignore it, else push value to array.function mergeAndSort(a1, a2) {
var matchCount = 0;
var ret = [];
for (var i = 0; i < a1.length; i++) {
var val = a2[matchCount];
if (a1[i] > val) {
ret.push(val)
matchCount++
i--;
continue;
}
if (a1[i] > 0) {
ret.push(a1[i]);
}
}
console.log(ret.join())
return ret;
}
var arrayOne = [3, 6, -1, 11, 15, -1, 23, 34, -1, 42]
var arrayTwo = [7, 19, 38];
var arrayThree = [1, 9, 28];
var arrayFour = [1,2,5]
mergeAndSort(arrayOne, arrayTwo)
mergeAndSort(arrayOne, arrayThree)
mergeAndSort(arrayOne, arrayFour)
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
Note: Not putting check for number of elements in arrayTwo
as its clearly mentioned in question that it will be same.