Merge two sorted arrays
Standard · Write code · about 10 min
a and b are both sorted ascending. Return one sorted array that holds every value of both. Walk both arrays once with two pointers; do not call a sort function.
Example 1
Input:
[[1,3,5],[2,3,8,9]]
Output:
[1,2,3,3,5,8,9]
Example 2
Input:
[[],[4]]
Output:
[4]
One side can be empty.
Constraints
- 0 ≤ a.length, b.length ≤ 1,000
- -10,000 ≤ a[i], b[i] ≤ 10,000
- a and b are sorted ascending
Learn the idea first: Merge sort, a visual lesson.
More Merge sort problems
- Recursion depth Warm-up
- Breaking a tie in the merge Warm-up
- Implement merge sort Standard
- Sort a linked list Standard
- Count inversions Challenge