Merge Two Sorted Lists Into a Padded Buffer
Arrays & HashingAuto-graded · 21 test casesLast updated
Merge a sorted list into the sorted prefix of a larger list that ends with unused slots, writing in place with constant extra memory.
A container list nums has room for m + n integers. Only its first m entries hold real data, and those entries are already in non-decreasing order. The remaining n trailing entries are reserved slots; whatever values they currently hold are irrelevant and must be ignored.
A second list extra contains exactly n integers, also in non-decreasing order.
Combine both sequences so that, once you are done, the first m + n entries of nums hold every real element from nums and every element of extra, arranged in non-decreasing order.
Rules:
- Do not allocate a new container: the merged result must be written directly into
nums, which is mutated. - Use only
O(1)additional memory beyond the input lists. - The trailing reserved slots may contain arbitrary values (zeros, leftovers, anything); never treat them as data.
- Return the modified
numslist itself.
Notes on ordering: when an element of nums and an element of extra are equal, either may be placed first; with plain integers the final list is identical either way.
Special cases you must handle:
- If
n == 0,numsis returned with its firstmentries unchanged. - If
m == 0, thenelements ofextraare copied intonumsin order. - All of
extramay be smaller than all ofnums, or vice versa. - Duplicate and negative values occur and need no special treatment.
Examples
Example 1
Input: merge_into_buffer([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3)
Output: [1, 2, 2, 3, 5, 6]
Example 2
Input: merge_into_buffer([1], 1, [], 0)
Output: [1]
Example 3
Input: merge_into_buffer([0], 0, [1], 1)
Output: [1]
Hints
Hint 1
Front-to-back merging would clobber unread values of nums; think about where the unused space actually lives.
Hint 2
Keep three indices: one at the last real element of nums, one at the last element of extra, one at the last slot of nums.
Hint 3
Write the larger of the two candidates into the last open slot, then step left. Stop as soon as extra is exhausted.
Hint 4
Guard against reading index -1 of nums (Python wraps silently), and remember leftover nums elements are already in place.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The tempting move is a classic merge from the front, but that is a trap here: the first writes would land on real entries of nums that have not been consumed yet, destroying them. Working around that with a temporary buffer or with repeated shifting costs either extra memory or quadratic time.
The key observation is that the unused room sits at the back of nums. So merge backwards, from the largest element down:
istarts atm - 1, the last real entry ofnums.jstarts atn - 1, the last entry ofextra.kstarts atm + n - 1, the last slot ofnums— the position the next-largest value must occupy.
Each round compares nums[i] with extra[j], copies the larger into nums[k], and moves that source pointer and k one step left. extra's element wins ties, which means it is placed further right; with integers this ordering choice is invisible.
The loop runs while j >= 0. Once extra is drained, whatever remains in nums[0..i] is already sorted and already sitting where it belongs, so nothing more needs to be done. The i >= 0 guard prevents reading nums[-1], which in Python silently wraps to the end of the list instead of erroring.
Correctness
Two facts establish the result.
No unread data is overwritten. The invariant k = i + j + 1 holds at the start ((m-1) + (n-1) + 1 = m + n - 1) and is preserved because each iteration decrements k and exactly one of i, j. While j >= 0 we have k >= i + 1 > i, so every write target is strictly to the right of all still-unread entries of nums.
Every write is final and correct. Since both inputs are sorted, nums[i] is the largest unplaced real entry of nums and extra[j] is the largest unplaced entry of extra. The larger of the two is the largest unplaced value overall, and it belongs exactly at the largest still-empty slot k. Inductively, the suffix nums[k..m+n-1] stays sorted and holds the largest values.
When j < 0, the invariant forces k = i, so the surviving prefix of nums is already in its final position. When i < 0 first, every remaining round takes from extra, filling the front of nums with extra's smallest values in order.
Complexity
- Time:
O(m + n)— at mostm + niterations, each doing constant work. - Extra space:
O(1)— only three integer indices; the output is written intonums.
Solution
from typing import List
def merge_into_buffer(nums: List[int], m: int, extra: List[int], n: int) -> List[int]:
i = m - 1 # last real element of nums
j = n - 1 # last element of extra
k = m + n - 1 # next slot to fill, from the back
while j >= 0:
if i >= 0 and nums[i] > extra[j]:
nums[k] = nums[i]
i -= 1
else:
nums[k] = extra[j]
j -= 1
k -= 1
return nums