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
Since they are both sorted, the order of arrayTwo
's items should match the order of -1
s in arrayOne
. Then the job becomes simple and can be implemented as follows;
function replaceMissing(a,b){
var i = 0;
return a.map(n => n < 0 ? b[i++] : n);
}
var arrayOne = [3,6,-1,11,15,-1,23,34,-1,42],
arrayTwo = [7,19,38];
result = replaceMissing(arrayOne,arrayTwo);
console.log(result);
Edit: I believe the upper solution does make more sense in the general logic of the question. If the position of -1s does not mean anything then what use do they have? Let's just delete the -1's and do a simple insertion of arrayTwo
items at proper indices in arrayOne
. This can very simply be done as follows.
function replaceMissing(a,b){
var j = b.length-1;
return b.concat(a.reduceRight((r,m,i) => (m < 0 ? r.splice(i,1)
: m < b[j] && r.splice(i+1,0,b.splice(j--,1)[0]),
r), a.slice()));
}
var arrayOne = [3,6,-1,11,15,-1,23,34,-1,42],
arrayTwo = [1,25,38];
result = replaceMissing(arrayOne,arrayTwo);
console.log(result);