TRT
Sign in
easyFoundationsLeetCode#merge#fill from the back

Merge sorted array

Merge a sorted array into another sorted array that has empty space at its end, in place, by filling from the back.

The Runtime Theory Team1 min read
Taught inTwo pointers on arraysTwo indexes moving through one array can reverse it, test a palindrome, compact it or merge into it, in one pass and with O(1) extra memory.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3

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

innums1 = [1], m = 1, nums2 = [], n = 0

out[1]

innums1 = [0], m = 0, nums2 = [1], n = 1

out[1]

nums1 has length m + n: its first m elements are sorted values and the last n are zeros to be overwritten. nums2 has n sorted values. Merge nums2 into nums1 so that nums1 ends up sorted.

Before you code

Merging from the front overwrites values of nums1 that haven't been compared yet. The free space is at the back, so fill it first.

Hints

  1. Use three indexes: i = m - 1, j = n - 1, and write = m + n - 1.
  2. While j >= 0, write the larger of nums1[i] and nums2[j] at write, and move that index and write back. Treat i < 0 as "nums1 is used up".
  3. When nums2 is used up, the rest of nums1 is already in place.

Production & complexity notes

When solving Merge sorted array on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Two pointers on arrays to reinforce the underlying pattern.

What it practices

One index per array, and choosing the direction that makes an in-place merge safe, from Two pointers on arrays.

Not started

Sign in to save your learning progress.

Sign in to save