Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Merge Two Sorted Arrays with Two Pointers

Merge two sorted lists into a single sorted list using the two-pointer technique.

Python practice8 minArrays – Fundamentals & PatternsBeginnerLast updated March 25, 2026

Problem statement

Given two sorted arrays (ascending order), return a new array that contains all elements from both input arrays in sorted order. Do not use built-in sort on the combined array; instead, take advantage of the fact that the two inputs are already sorted and merge them in O(n+m) time and O(n+m) additional space.

Task

Implement an efficient merge of two sorted arrays that returns a new sorted array containing all elements from both inputs.

Examples

Basic merge

Input

a = [1, 3, 5], b = [2, 4, 6]

Output

[1, 2, 3, 4, 5, 6]

Alternate elements from the two arrays in sorted order.

Input format

Two lists of integers: merge_sorted_arrays(a, b).

Output format

A single list of integers sorted in ascending order.

Constraints

0 <= len(a), len(b) <= 10^5. Values can be negative, zero, or positive. Aim for O(n + m) time and O(n + m) space.

Samples

Sample 1

Input

merge_sorted_arrays([1,2], [3,4])

Output

[1, 2, 3, 4]

Simple concatenation in order using merge.