Examples
Write mergeSorted so that the following cases hold.
- Input
mergeSorted([1,3,5], [2,4,6])Output[1,2,3,4,5,6] - Input
mergeSorted([], [1,2])Output[1,2] - Input
mergeSorted([1,1], [1])Output[1,1,1]
1 more hidden test cases - 4 in total will be graded.
Answer
js
function mergeSorted(a, b) {
const out = [];
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
out.push(a[i] <= b[j] ? a[i++] : b[j++]);
}
while (i < a.length) out.push(a[i++]);
while (j < b.length) out.push(b[j++]);
return out;
}
mergeSorted([1, 3, 5], [2, 4, 6]); // [1, 2, 3, 4, 5, 6]
Two pointers give O(n + m), while a.concat(b).sort() is O(n log n). Use <= to stay stable and handle duplicates correctly.
