Drill

ProblemsJavaScript › patterns

Merge two sorted queues

mediumpatternsTwo pointersArraysJavaScript

A worker pulls from two queues that are each already sorted, and must hand downstream one combined sorted stream.

mergeSorted(first: list<int>, second: list<int>) → list<int>

Solve it in the editor →

Where you start

function mergeSorted(first, second) {
  
}

Worked examples

CallResult
mergeSorted([1,2,4], [1,3])[1,1,2,3,4]
mergeSorted([], [1,2])[1,2]
mergeSorted([1,2], [])[1,2]
mergeSorted([], [])[]

Hint

Two pointers, one for each list. Take the smaller head, advance that pointer, and when one side runs out the rest of the other side follows.

Reference solution in JavaScript
function mergeSorted(first, second) {
  const merged = [];
  let i = 0, j = 0;
  while (i < first.length && j < second.length) {
    if (first[i] <= second[j]) merged.push(first[i++]);
    else merged.push(second[j++]);
  }
  while (i < first.length) merged.push(first[i++]);
  while (j < second.length) merged.push(second[j++]);
  return merged;
}

The same problem in another language

More patterns problems in JavaScript