easyarraytwo-pointer

Merge Two Sorted Arrays

Given two sorted arrays, print a single merged sorted output.

Problem

Statement

Two sorted inputs, one sorted output. The two-pointer walk runs in O(n + m) — advance the pointer whose current element is smaller, emit it, repeat. When one array runs out, drain the other.

This is the merge step of merge sort and one of the most fundamental array operations. Every sort-adjacent algorithm eventually calls something like it.

Read array A on line 1, array B on line 2. Print merged on line 3.

Worked cases

Examples

Input
1 3 5
2 4 6
Output
1 2 3 4 5 6
Input

1 2 3
Output
1 2 3
NoteEmpty A → output is B.
Bounds

Constraints

  • 0 ≤ |A|, |B| ≤ 10^5
  • Both arrays are sorted in ascending order.
Reference

Sample solutions

Runnable starter code. Click "Try in playground" to open pre-loaded with the test fixtures.

Python
a = list(map(int, input().split()))
b = list(map(int, input().split()))
i = j = 0
out = []
while i < len(a) and j < len(b):
    if a[i] <= b[j]: out.append(a[i]); i += 1
    else:            out.append(b[j]); j += 1
out.extend(a[i:]); out.extend(b[j:])
print(*out)
Java
import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] a = parse(sc.nextLine());
        int[] b = parse(sc.nextLine());
        StringBuilder sb = new StringBuilder();
        int i = 0, j = 0;
        while (i < a.length && j < b.length) sb.append(a[i] <= b[j] ? a[i++] : b[j++]).append(' ');
        while (i < a.length) sb.append(a[i++]).append(' ');
        while (j < b.length) sb.append(b[j++]).append(' ');
        System.out.println(sb.toString().trim());
    }
    static int[] parse(String line) {
        if (line == null || line.isEmpty()) return new int[0];
        String[] parts = line.trim().split("\\s+");
        int[] r = new int[parts.length];
        for (int k = 0; k < parts.length; k++) r[k] = Integer.parseInt(parts[k]);
        return r;
    }
}
C++
#include <bits/stdc++.h>
using namespace std;

vector<int> parse(const string &line) {
    vector<int> v; stringstream ss(line); int x; while (ss >> x) v.push_back(x);
    return v;
}

int main() {
    string la, lb; getline(cin, la); getline(cin, lb);
    auto a = parse(la), b = parse(lb);
    size_t i = 0, j = 0; string out;
    while (i < a.size() && j < b.size()) {
        int v = a[i] <= b[j] ? a[i++] : b[j++];
        out += to_string(v) + ' ';
    }
    while (i < a.size()) out += to_string(a[i++]) + ' ';
    while (j < b.size()) out += to_string(b[j++]) + ' ';
    if (!out.empty()) out.pop_back();
    cout << out << "\n";
}
Also try