Challenge: Merge Two Sorted Lists
Completed
Read two sorted lists and merge them into one sorted list using two pointers (don't just join them and sort).
Input
Line 1: n, then n sorted numbers. Line 2: m, then m sorted numbers.
Output
The merged sorted list, separated by spaces.
Example
Input
3 1 4 7 4 2 3 8 9
Output
1 2 3 4 7 8 9
Editor
C++
Hints
Compare a[i] and b[j]; take the smaller and move that pointer.
Copy whatever is left over at the end.
Solution explanation
Every number is taken once: O(n + m). This is the heart of merge sort (Module 8).
Show solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
cin >> n;
vector<int> a(n);
for (int& x : a) cin >> x;
cin >> m;
vector<int> b(m);
for (int& x : b) cin >> x;
vector<int> out;
int i = 0, j = 0;
while (i < n && j < m) {
if (a[i] <= b[j]) out.push_back(a[i++]);
else out.push_back(b[j++]);
}
while (i < n) out.push_back(a[i++]);
while (j < m) out.push_back(b[j++]);
for (size_t k = 0; k < out.size(); k++) cout << out[k] << (k + 1 < out.size() ? " " : "\n");
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module