Skills101
← All coding problems

Merge Sorted Array

easyTwo Pointers+10 XPTime limit 2s

Merge two arrays that are each sorted in non-decreasing order into one sorted array.

Input:

  • line 1: m n — the sizes of the two arrays
  • line 2: the m values of the first array (empty if m = 0)
  • line 3: the n values of the second array (empty, or missing, if n = 0)

Output: all m + n values in sorted order on one line.

Constraints: 0 ≤ m, n ≤ 10⁵, 1 ≤ m + n, −10⁹ ≤ value ≤ 10⁹.

Tip: reading all numbers as whitespace-separated tokens (instead of line by line) handles the empty lines for free.

Challenge: the classic version merges in place into the first array (which has room for both). The trick: fill it from the back, comparing the largest remaining values. Here, aim for O(m + n) — don't just concatenate and sort.

Sample input 1

3 3
1 2 3
2 5 6

Sample output 1

1 2 2 3 5 6

Sample input 2

1 0
1

Sample output 2

1

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.