Skip to content
RED SAGSkills

Merge Two Sorted Lists

You have two arrays a and b, each already sorted in non-decreasing order. Return a single new array containing every element of both, also sorted in non-decreasing order.

Try to do it in O(n + m) time without calling a sort function.

Example 1

Input: a = [1, 4, 9], b = [2, 4, 10, 12]
Output: [1, 2, 4, 4, 9, 10, 12]

Example 2

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

Constraints

  • 0 <= a.length, b.length <= 10^5
  • -10^9 <= a[i], b[i] <= 10^9
Hint 1

Keep one pointer in each array.

Hint 2

Repeatedly take the smaller front element, then copy whatever is left.

Good practice for: Frontend Developer, Backend Developer, Full Stack Developer, Mobile App Developer, Game Developer, Automation Test Engineer, Data Engineer

Run checks your code on 2 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.