Merge Two Sorted Arrays
Merge Two Sorted Arrays
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
Output
- •
0 ≤ n, m ≤ 10^5, -10^9 ≤ elements ≤ 10^9
More Arrays problems
Browse all coding problems →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