⌘K
Flycodx

Merge Two Sorted Arrays

Merge Two Sorted Arrays

EasyArrays100% accepted

Given two integer arrays that are each sorted in non-decreasing order, merge them into a single sorted array and print all elements in order.

Input format — only if your code reads from stdin

Input format: - First line: two integers n and m (sizes of the two arrays) - Second line: n space-separated integers (first sorted array) - Third line: m space-separated integers (second sorted array) Output: the merged sorted array as space-separated integers. Note: either array may be empty (n or m can be 0).

Approach

Use two pointers — one per array. Compare the current elements and always pick the smaller one. When one array is exhausted, append the remainder of the other.

Input

3 4 1 3 5 2 4 6 8

Output

1 2 3 4 5 6 8
  • •0 ≤ n, m ≤ 10^5, -10^9 ≤ elements ≤ 10^9
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3