David to DSAEnglish • 2 days ago

How do you merge two sorted arrays in-place from the back without overwriting unmerged elements?

message-square
0
1
How do you merge two sorted arrays in-place from the back without overwriting unmerged elements?
David to DSAEnglish • 2 days ago

Merging Two Sorted Arrays In-Place: The Reverse Three-Pointer Technique

Given two sorted integer arrays nums1 of size $m + n$ (with $m$ active elements and $n$ trailing blank/zero slots) and nums2 of size $n$, the task is to merge nums2 into nums1 as a single sorted array.

Merging from the front (index 0) requires shifting elements rightward, resulting in an inefficient $O(m \cdot n)$ time complexity, or allocating an auxiliary array ($O(m)$ space).

By merging from the back (from index $m + n - 1$ down to 0), we populate the largest elements first into the empty trailing space. This ensures unmerged elements in nums1 are never prematurely overwritten, achieving an optimal $O(m + n)$ time and strictly $O(1)$ auxiliary space.


The Mathematical Invariant: Why Overwriting Never Occurs

Let:

  • $p_1$ point to the last active element of nums1 (initially $m - 1$).
  • $p_2$ point to the last element of nums2 (initially $n - 1$).
  • $p$ point to the write destination at the back of nums1 (initially $m + n - 1$).

At any point during the merge:

  • The number of elements written to the back is $(m + n - 1) - p$.
  • The number of unmerged elements originally belonging to nums1 is $p_1 + 1$.
  • The empty write head $p$ satisfies: $$p = p_1 + (p_2 + 1)$$

Because $p_2 \ge 0$ while elements remain in nums2, it is mathematically guaranteed that: $$p \ge p_1 + 1 > p_1$$

The write head $p$ is always strictly ahead of the read pointer $p_1$. Therefore, writing into index $p$ cannot overwrite an unexamined element at $p_1$.


Algorithmic Execution Steps

  1. Initialize Three Pointers:

    • $p_1 = m - 1$ (reads from nums1)
    • $p_2 = n - 1$ (reads from nums2)
    • $p = m + n - 1$ (writes to nums1)
  2. Step-by-Step Backwards Merge:

    • While both $p_1 \ge 0$ and $p_2 \ge 0$:
      • Compare nums1[p1] with nums2[p2].
      • Place the larger of the two at nums1[p].
      • Decrement $p$ and the pointer of the chosen element.
  3. Handle Leftover Elements:

    • If p2 >= 0: Any remaining elements in nums2 are strictly smaller than everything placed so far. Copy them directly into nums1[0 ... p].
    • If p1 >= 0: Any remaining elements in nums1 are already in their correct sorted positions. No further action is needed.

Trace Walkthrough: nums1 = [1, 2, 3, 0, 0, 0], $m = 3$; nums2 = [2, 5, 6], $n = 3$

  • Start: $p_1 = 2$ (3), $p_2 = 2$ (6), $p = 5$
Step nums1[p1] nums2[p2] Comparison Placed at nums1[p] Array State Pointers After Step
1 $3$ $6$ $6 > 3$ nums1[5] = 6 [1, 2, 3, 0, 0, 6] $p_1=2, p_2=1, p=4$
2 $3$ $5$ $5 > 3$ nums1[4] = 5 [1, 2, 3, 0, 5, 6] $p_1=2, p_2=0, p=3$
3 $3$ $2$ $3 > 2$ nums1[3] = 3 [1, 2, 3, 3, 5, 6] $p_1=1, p_2=0, p=2$
4 $2$ $2$ $2 \ge 2$ nums1[2] = 2 [1, 2, 2, 3, 5, 6] $p_1=1, p_2=-1, p=1$
  • Loop terminates because $p_2 < 0$. Leftover elements in nums1 ([1, 2]) are already correctly placed.

Implementation (C++ and Python)

C++ Implementation

#include <vector>

void merge(std::vector<int>& nums1, int m, const std::vector<int>& nums2, int n) {
    int p1 = m - 1;          // Last active element in nums1
    int p2 = n - 1;          // Last element in nums2
    int p = m + n - 1;       // Backmost slot in nums1

    // Backwards comparison loop
    while (p1 >= 0 && p2 >= 0) {
        if (nums1[p1] > nums2[p2]) {
            nums1[p] = nums1[p1];
            p1--;
        } else {
            nums1[p] = nums2[p2];
            p2--;
        }
        p--;
    }

    // Copy remaining elements from nums2 if any exist
    // (If p2 < 0, nums1's remaining elements are already in place)
    while (p2 >= 0) {
        nums1[p] = nums2[p2];
        p2--;
        p--;
    }
}

Python Implementation

def merge(nums1: list[int], m: int, nums2: list[int], n: int) -> None:
    """
    Merges nums2 into nums1 in-place in non-decreasing order.
    Modifies nums1 directly in O(m + n) time and O(1) space.
    """
    p1 = m - 1
    p2 = n - 1
    p = m + n - 1

    while p1 >= 0 and p2 >= 0:
        if nums1[p1] > nums2[p2]:
            nums1[p] = nums1[p1]
            p1 -= 1
        else:
            nums1[p] = nums2[p2]
            p2 -= 1
        p -= 1

    # If nums2 still has elements left, copy them into the beginning of nums1
    while p2 >= 0:
        nums1[p] = nums2[p2]
        p2 -= 1
        p -= 1

Complexity Analysis

Metric Complexity Explanation
Time Complexity $O(m + n)$ Each iteration of the loop places exactly one element into its final position at pointer $p$. The total number of element placements is strictly $m + n$.
Auxiliary Space $O(1)$ Reuses the allocated trailing buffer of nums1. Only three pointer integer indices (p1, p2, p) are tracked.

Important Edge Cases Handled

  • nums1 is initially empty ($m = 0$): The first loop is bypassed entirely; the second loop flushes all elements of nums2 directly into nums1.
  • nums2 is initially empty ($n = 0$): $p_2 = -1$ at initialization, so neither loop executes and nums1 is preserved as-is without redundant writes.
  • All elements in nums2 are strictly larger than nums1: nums2 fills indices $m$ through $m + n - 1$ consecutively without shifting any elements originally in nums1.