← All coursesDSA Foundations

Lesson 8 of 19

Merging sorted arrays

Two rows of number cards are each sorted from low to high. Build one sorted row by choosing between the first unused cards. On a tie, take the card from the left row first.

Only the two front cards can come next

The front of each sorted row holds its smallest unused value. Copy the smaller front to the output and advance only that row’s index. Choosing the left front on a tie keeps equal cards in their original order when the left input precedes the right. For n and m input cards, merging takes O(n + m) time and O(n + m) space for the output.

Work through an example

Merge the left row [2, 5] with the right row [1, 2, 8]. What is the output if the left card wins a tie?

Step-by-step solution
  1. Compare 2 with 1. Take the right 1, leaving a 2 at the front of each row.
  2. Take the left 2 on the tie. The right 2 now comes before the left 5. Both copies of 2 are in the output.
  3. Take 5 before 8. The left row is empty, so copy the remaining 8 to finish [1, 2, 2, 5, 8].
JavaScript example
const left = [2, 5], right = [1, 2, 8];
const merged = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
  if (left[i] <= right[j]) merged.push(left[i++]);
  else merged.push(right[j++]);
}
while (i < left.length) merged.push(left[i++]);
while (j < right.length) merged.push(right[j++]);
merged;
DSA compiler

Try it yourself

Finish the animation to unlock this question.

The left row has run out. The right row still holds 6 and 8 in that order. What belongs at the end of the output?

Play Merge Mixer · Related exercise · Merging Sorted Arrays · Take the end-of-stage challenge