Problem 14
Merge Two Sorted Arrays
Easy · 10 pts · Array, Two Pointers, Sorting
Problem
You are given two arrays, each sorted in non-decreasing order, with N and M elements. Merge them into one sorted array that contains all N + M elements, keeping duplicates, and print it. One of the arrays may be empty. Use two pointers, one per array: repeatedly take the smaller of the two current elements and advance that pointer. When one array runs out, copy the rest of the other. This takes O(N + M) time, faster than joining the arrays and sorting.
Input
First line: integers N and M. Second line: N integers. Third line: M integers.
Output
Print all N + M elements in sorted order, separated by spaces.
Constraints
0 <= N, M; 1 <= N + M <= 100000; -10^9 <= values <= 10^9
Example input
3 3 1 3 5 2 4 6
Example output
1 2 3 4 5 6
Explanation
Merging 1 3 5 with 2 4 6: take 1 (smaller than 2), then 2, then 3, then 4, then 5, then 6. The result is 1 2 3 4 5 6.