beginner · two pointers · merging · in place

Merge two sorted lists into the first one

Problem

Two lists are sorted ascending. The first has exactly enough free slots at its end to hold the second. Merge the second into the first so the first holds all values in ascending order, without allocating another list.

Constraints

  • the first list holds m values followed by n free slots; the second holds n values
  • m + n ≤ 32
  • values from −999 to 999

Examples

first = [1, 4, 7, _, _], second = [2, 5] → [1, 2, 4, 5, 7]

Show the solution

Merge from the back

The largest remaining value always goes into the last free slot, and writing there never overwrites an unread value of the first list.

Why it is correct

Invariant: positions after k hold the largest values, sorted. The write position k is always ≥ i (k − i = number of second-list values left, j + 1 ≥ 0), so no unread first-list value is overwritten. When the second list is used up, the remaining first-list values are already in place.

Complexity

Time O(m + n), extra space O(1). Every iteration places one value; there are m + n slots and the loop stops once the n second-list values are placed.

For contrast: Copy the second list into the free slots and sort. That costs O((m + n) log(m + n)) time and depends on the sort space.

Edge cases

  • Empty second list: nothing to do.
  • Empty first part (m = 0): copy the second list.
  • Equal values: either order is valid.

Common mistakes

  • Merging from the front and overwriting the first list.
  • Looping while i ≥ 0 instead of while j ≥ 0, and leaving second-list values behind.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class MergeSortedArrays
{
    /// <summary>Merges sorted second into sorted first[0..m), which has exactly second.Length free slots after it. O(m + n), O(1) space.</summary>
    public static void Merge(int[] first, int m, int[] second)
    {
        int i = m - 1, j = second.Length - 1, k = first.Length - 1;
        while (j >= 0)
        {
            if (i >= 0 && first[i] > second[j])
                first[k--] = first[i--];
            else
                first[k--] = second[j--];
        }
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/MergeSortedArrays.cs

from collections.abc import Sequence
 
 
def merge(first: list[int], m: int, second: Sequence[int]) -> None:
    """Merge sorted second into sorted first[:m], which has exactly len(second) free slots after it. O(m + n), O(1) space."""
    i, j, k = m - 1, len(second) - 1, len(first) - 1
    while j >= 0:
        if i >= 0 and first[i] > second[j]:
            first[k] = first[i]
            i, k = i - 1, k - 1
        else:
            first[k] = second[j]
            j, k = j - 1, k - 1

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/merge_sorted_arrays.py

package dev.bekadan.dsa.problems;
 
public final class MergeSortedArrays {
    private MergeSortedArrays() {
    }
 
    /** Merges sorted second into sorted first[0..m), which has exactly second.length free slots after it. O(m + n), O(1) space. */
    public static void merge(int[] first, int m, int[] second) {
        int i = m - 1, j = second.length - 1, k = first.length - 1;
        while (j >= 0) {
            if (i >= 0 && first[i] > second[j]) {
                first[k--] = first[i--];
            } else {
                first[k--] = second[j--];
            }
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/MergeSortedArrays.java

#pragma once
 
#include <cstddef>
#include <span>
 
namespace bekadan::dsa::problems {
 
// Merges sorted `second` into sorted first[0, m), which has exactly second.size() free slots after it. O(m + n).
inline void merge_sorted_arrays(std::span<int> first, std::size_t m, std::span<const int> second) {
    std::ptrdiff_t i = static_cast<std::ptrdiff_t>(m) - 1, j = std::ssize(second) - 1, k = std::ssize(first) - 1;
    const auto at = [](auto span, std::ptrdiff_t index) -> decltype(auto) { return span[static_cast<std::size_t>(index)]; };
    while (j >= 0) {
        if (i >= 0 && at(first, i) > at(second, j))
            at(first, k--) = at(first, i--);
        else
            at(first, k--) = at(second, j--);
    }
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/merge_sorted_arrays.hpp