Fill Spare Slots and Sort One Buffer In Place
Heaps, Sorting & SearchModel answerLast updated
Combine two unsorted integer lists into the first, which has spare room at its end, so it ends up fully ascending, without using placeholder values to locate the data.
Combine Two Lists Into One Buffer
You get two unsorted integer lists, a and b, and two counts, m and n.
ahas lengthm + n. Only its firstmentries are real data. The lastnentries are filler of arbitrary value (zeros, garbage, or even numbers that look legitimate).bhas lengthn, and all of its entries are real data.
Rewrite a so that it holds all m + n real values in non-decreasing order. The change must happen in place on the list the caller passed in. Nothing is returned.
def merge_and_sort(a: list[int], m: int, b: list[int], n: int) -> None:
"""
Do not return anything, modify a in-place instead.
"""
pass
Examples
Example 1
a = [5, 1, 9, 0, 0, 0], m = 3, b = [8, 2, 4], n = 3
a after the call -> [1, 2, 4, 5, 8, 9]
Example 2
a = [3, -1, 0, 0], m = 2, b = [0, -5], n = 2
a after the call -> [-5, -1, 0, 3]
A 0 can be a genuine value or filler, so decide what is real using only m and n, never the values themselves.
Constraints
len(a) == m + n,len(b) == n0 <= m, n <= 10^5, and1 <= m + n <= 10^5-10^9 <= a[i], b[i] <= 10^9
What to cover in your answer
- Your approach and why it is correct, including the edge cases
m = 0,n = 0, duplicates, negatives and filler that equals real values. - Time and space complexity, stated honestly (including what the library sort costs in memory).
- How the approach changes if
a[:m]is already sorted andnis tiny compared withm. - How you would achieve strictly O(1) auxiliary space without a library sort.
- Working code.
Hints
Hint 1
Neither input is sorted, so the well-known back-to-front merge of two sorted lists cannot be applied directly. Think about what the simplest two-step plan looks like.
Hint 2
Use `m` to find where real data ends. Overwrite the last `n` slots by position, never by searching for zeros, and make sure you mutate the caller's list rather than rebinding the name `a`.
Hint 3
For the follow-ups: if `a[:m]` is already sorted, sorting only `b` and merging from the back is enough. For strict O(1) extra memory, a library sort will not qualify, so consider an in-place comparison sort with no recursion.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since both inputs are unsorted, there is nothing to exploit beyond a full sort of the combined data. The plan has two steps:
- Place. Write every element of
binto the reserved tail ofa, positionsmthroughm + n - 1. The boundary comes fromm, never from inspecting values. - Sort. Sort all of
ain place.
After step 1, a contains exactly the multiset of the m + n real values. Step 2 orders them.
Why it is correct
- Exact placement. Because
len(a) == m + nandlen(b) == n, the slicea[m:m+n]has exactlynslots. Assigningbinto it replaces every filler value and touches nothing else. - Fillers never matter. We overwrite by position. A real
0(Example 2) is treated like any other number. A solution that scans for the first0to find the end of the data is wrong. - In-place contract.
a[m:m+n] = banda.sort()both mutate the caller's list. Writinga = sorted(a[:m] + b)only rebinds a local name, and the caller sees no change. This is the most common bug.
Code
def merge_and_sort(a: list[int], m: int, b: list[int], n: int) -> None:
# Overwrite the n filler slots; the length of a is unchanged.
a[m:m + n] = b
# Sort the whole list in place.
a.sort()
Trace for Example 1: [5,1,9,0,0,0] becomes [5,1,9,8,2,4] after placement and [1,2,4,5,8,9] after sorting.
An explicit loop for i in range(n): a[m + i] = b[i] is equivalent and perhaps clearer.
Edge cases
| Case | Behavior |
|---|---|
m = 0 | a[0:n] = b replaces all filler, then sort. |
n = 0 | Assigning an empty list to an empty slice is a no-op; just sort the first m entries (which is all of a). |
| Duplicates | All copies are kept; nothing is deduplicated. |
Negatives, ±10^9 | Python integers do not overflow. In other languages, compare rather than subtract. |
| Filler equals a real value | Irrelevant, since only m and n are used. |
Complexity
Let N = m + n.
- Time: O(n) for placement plus O(N log N) for sorting, so O(N log N).
- Space: no result array is allocated, but Timsort may use up to about N/2 temporary elements while merging runs. So the honest statement is O(N) auxiliary space in the worst case, not O(1).
Trade-off: sort the combined list vs. sort each part then merge
- Sort
a[:m](O(m log m)) andb(O(n log n)), then merge from the back with three pointers: one atm-1, one atn-1, one write index atm+n-1, always writing the larger value. Writing from the back guarantees no unread element ofais overwritten. The merge is O(N) time and O(1) space. - Overall this is still O(N log N), because
m log m + n log n <= N log N. It is not asymptotically better and needs more code. Timsort on the combined array already finds runs and merges them, so the simple version is usually the right call.
Variant: m huge, n tiny, a[:m] already sorted
Here sorting everything wastes work.
- Sort
bin O(n log n), which is trivial for smalln. - Merge from the back in O(m + n) time and O(1) space.
This is essentially optimal in element moves, since an element of b may need to pass over up to m entries. Binary search can locate insertion points in O(log m), but the shifting still costs O(m). If you simply place b in the tail and call sort(), Timsort detects the long sorted run and runs in near-linear time, so the short version is also acceptable.
If a[:m] is not sorted, you must sort it anyway, so the cost is Θ(m log m) regardless of strategy.
Strict O(1) auxiliary space, no library sort
Use heapsort after placement. It is O(N log N) time and truly O(1) extra space when sift-down is iterative. Quicksort needs O(log N) stack even if you recurse on the smaller side first, so it does not meet a strict O(1) bound. Merge sort needs a buffer.
def _sift_down(a, start, end):
root = start
while 2 * root + 1 < end:
child = 2 * root + 1
if child + 1 < end and a[child + 1] > a[child]:
child += 1
if a[root] >= a[child]:
return
a[root], a[child] = a[child], a[root]
root = child
def merge_and_sort_o1(a, m, b, n):
for i in range(n):
a[m + i] = b[i]
N = m + n
for start in range(N // 2 - 1, -1, -1): # build max-heap
_sift_down(a, start, N)
for end in range(N - 1, 0, -1): # move max to the end
a[0], a[end] = a[end], a[0]
_sift_down(a, 0, end)
Heapsort is not stable, which is irrelevant for plain integers.
Common mistakes
- Locating the end of the data by searching for
0or any sentinel. - Rebinding
ainstead of mutating it. - Applying the two-pointer back-merge directly to unsorted inputs, which yields a wrong result.
- Claiming O(1) space while using a library sort without qualification.
- Forgetting that
m = 0orn = 0must work without special-casing.