#C3981. Merge Two Sorted Arrays

    ID: 47468 Type: Default 1000ms 256MiB

Merge Two Sorted Arrays

Merge Two Sorted Arrays

You are given T test cases. For each test case, you are provided with two sorted arrays. Your task is to merge these two arrays into a single sorted array.

The merging process should be done in linear time using a two-pointer technique. This problem is a classic example of array merging and requires careful handling of multiple input arrays.

Specifically, for each test case:

  • The first line contains an integer n, the number of elements in the first array.
  • The second line contains n space-separated integers in non-decreasing order.
  • The third line contains an integer m, the number of elements in the second array.
  • The fourth line contains m space-separated integers in non-decreasing order.

You need to merge these two arrays and output the merged sorted array as a space-separated string. The algorithm should run in O(n+m) time per test case.

The merging logic can be summarized by the following pseudo-code using two pointers:

[ \text{while } i < n \text{ and } j < m:\newline \quad \text{if } A[i] \leq B[j] \text{ then }\newline \quad\quad \text{append } A[i] \text{ and increment } i \newline \quad \text{else }\newline \quad\quad \text{append } B[j] \text{ and increment } j \newline \text{append the rest of } A \text{ (if any)}\newline \text{append the rest of } B \text{ (if any)} ]

inputFormat

The input is read from stdin and has the following format:

  1. An integer T representing the number of test cases.
  2. For each test case, four lines are provided:
    • The first line: an integer n, the number of elements in the first array.
    • The second line: n space-separated integers (sorted in non-decreasing order).
    • The third line: an integer m, the number of elements in the second array.
    • The fourth line: m space-separated integers (sorted in non-decreasing order).

outputFormat

For each test case, output the merged sorted array as a single line of space-separated integers to stdout.

## sample
3
3
1 3 5
4
2 4 6 8
2
-1 0
3
-2 -2 2
5
-10 -3 0 7 9
6
-5 -4 -2 1 3 8
1 2 3 4 5 6 8

-2 -2 -1 0 2 -10 -5 -4 -3 -2 0 1 3 7 8 9

</p>