Coding problem · Easy · Basics

Merge Two Sorted Arrays

Easy Algorithms & data structures

Given two arrays a and b, each sorted in ascending order, return one sorted array containing all their elements.

Example 1

Input: a = [1,3,5], b = [2,4,6]
Output: [1,2,3,4,5,6]

Example 2

Input: a = [], b = [1]
Output: [1]

Hints

Hint 1

Use one index for each array.

Hint 2

Repeatedly take the smaller of the two current elements; when one array runs out, copy the rest of the other.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n + m) · Space O(n + m)

The two-pointer merge from merge sort: compare a[i] and b[j], take the smaller, advance that pointer. O(n + m), better than concatenating and re-sorting.

Reference solution

function mergeSorted(a, b) {
  const out = [];
  let i = 0, j = 0;
  while (i < a.length && j < b.length) out.push(a[i] <= b[j] ? a[i++] : b[j++]);
  return out.concat(a.slice(i), b.slice(j));
}

Was this page helpful?