Problems › Sorting

Merge Two Sorted Arrays

Difficulty: Easy · Topic: Sorting

Given two arrays a and b, each already sorted ascending, return a single sorted array containing all of their elements. This is exactly the merge step of merge sort — walk both with two pointers, always taking the smaller front.

Examples

merge_sorted([1,3,5], [2,4,6])
→ [1,2,3,4,5,6]

Interleave by always taking the smaller head.

merge_sorted([], [1,2])
→ [1,2]

Target complexity: time O(m + n), space O(m + n)

Write your solution in Python and run it against hidden tests right on this page. Progressive hints and Python + C++ reference solutions are included.

Learn the idea first: the lesson for this problem.

More Sorting problems