Arrays — Visual Learning

Merge Two Sorted Arrays —
Compare, pick, advance.

Merging two sorted arrays into one sorted array is one of the most fundamental operations in DSA — it's the core step of merge sort. Two pointers walk through both arrays simultaneously, always picking the smaller element. Watch both pointers advance on LearnBug and the merge step of merge sort will never confuse you again.

O(n+m)Time complexity
O(n+m)Space complexity
PythonLanguage

What is Merge Sorted Arrays?

Given two sorted arrays A and B, produce a single sorted array containing all elements from both. Use two pointers — i on A and j on B. At each step, compare A[i] and B[j], append the smaller one to the result, and advance that pointer. When one array is exhausted, append all remaining elements from the other.

Why visualization changes everything

In code, tracking two indices and a result array simultaneously is easy to lose track of. On LearnBug, both source arrays are highlighted in parallel — you see which pointer moves, which element gets picked, and the result array grow cell by cell. The "drain remaining" step at the end becomes obvious once you watch it happen.

YouTube — Merge Sorted Arrays Explained
📺 Drop your YouTube embed here
LearnBug — two pointers merging in real time
🖼 Add a LearnBug screenshot here
Walkthrough

Merging step by step

A = [1, 3, 5, 7]  |  B = [2, 4, 6, 8]  →  Result: [1, 2, 3, 4, 5, 6, 7, 8]

1

Compare A[0]=1 vs B[0]=2 → pick 1

1 < 2. Append 1 to result. Advance i to 1.

A

1i
3
5
7

B

2j
4
6
8

Result

1
·
·
·
·
·
·
·
2

Compare A[1]=3 vs B[0]=2 → pick 2

2 < 3. Append 2. Advance j to 1.

A

1
3i
5
7

B

2j
4
6
8

Result

1
2
·
·
·
·
·
·
3

Steps 3–7: alternating picks

3 vs 4 → 3. 5 vs 4 → 4. 5 vs 6 → 5. 7 vs 6 → 6. 7 vs 8 → 7. Both pointers advance cleanly — result fills in sorted order.

1
2
3
4
5
6
7
·

Result so far: [1, 2, 3, 4, 5, 6, 7]

4

A exhausted — drain remaining B

i has passed the end of A. Just append everything left in B (8) directly — no comparisons needed since B is already sorted.

1
2
3
4
5
6
7
8

Final result: [1, 2, 3, 4, 5, 6, 7, 8]

Python Code

Two implementations

PythonMerge into new array — O(n+m) space
def merge_sorted_arrays(A, B):
    i, j   = 0, 0
    result = []

    while i < len(A) and j < len(B):
        if A[i] <= B[j]:
            result.append(A[i])
            i += 1
        else:
            result.append(B[j])
            j += 1

    result.extend(A[i:])   # drain remaining A
    result.extend(B[j:])   # drain remaining B
    return result
PythonMerge in-place (LeetCode 88 style) — from the back
def merge_in_place(nums1, m, nums2, n):
    # nums1 has extra space at the end for n elements
    i, j, k = m - 1, n - 1, m + n - 1

    while i >= 0 and j >= 0:
        if nums1[i] > nums2[j]:
            nums1[k] = nums1[i]; i -= 1
        else:
            nums1[k] = nums2[j]; j -= 1
        k -= 1

    while j >= 0:       # remaining nums2
        nums1[k] = nums2[j]; j -= 1; k -= 1

Time & Space Complexity

TimeO(n + m)Each element from both arrays is visited exactly once
Space — new arrayO(n + m)Result array holds all n + m elements
Space — in-placeO(1)Merge from back into pre-allocated space in nums1
Why fill from back?No overwrite riskFilling from the largest position means you never overwrite unread elements

Frequently asked questions

Why does the in-place version fill from the back?

If you filled from the front, placing a large element from nums2 at position 0 would overwrite an element from nums1 that hasn't been processed yet. Filling from the back places the largest elements at the end of the pre-allocated space — positions already past the active data — so nothing gets overwritten before it's been read.

What happens if one array is much longer than the other?

The extend call (or the drain while loop) handles this. When one pointer exhausts its array, you just copy the rest of the other array into result — no comparisons needed since the remaining elements are already sorted and all larger than everything already added.

How does merging relate to merge sort?

Merge sort works by recursively splitting an array into halves until you have single elements (trivially sorted), then merging adjacent sorted halves back up. The merge step you see here is exactly what runs at every level of that merge sort tree. Understanding this merge is the key to understanding merge sort.

Can you merge K sorted arrays efficiently?

Yes — use a min-heap of size K. Push the first element from each array into the heap. Repeatedly pop the minimum, append it to result, and push the next element from that array. Total time: O(N log K) where N is the total number of elements. This is a classic interview problem (LeetCode 23 — Merge K Sorted Lists).

What is the LeetCode problem for this?

LeetCode 88 — Merge Sorted Array. It uses the in-place back-fill approach where nums1 has extra space at the end. The key insight interviewers look for is filling from back to front to avoid the overwrite problem. Also related: LC 21 (Merge Two Sorted Lists) applies the same logic to linked lists.

Watch both pointers merge on your own arrays

Paste two sorted arrays into LearnBug and see every comparison and pointer advance step by step.

Open Playground →