Fill a Padded Sorted Buffer from a Second Sorted List
Arrays & HashingAuto-graded · 20 test casesLast updated
Merge two sorted lists into the first, which has trailing spare slots, without extra memory; tests back-to-front two-pointer merging.
You are given two integer lists that are each sorted in non-decreasing order.
bufferhas lengtha_len + b_len. Only its firsta_lenentries are meaningful; the finalb_lenentries are placeholder slots that can be overwritten freely.otherhas lengthb_lenand holdsb_lenmeaningful values.
Combine the meaningful values of both lists so that buffer ends up holding all a_len + b_len values in non-decreasing order. The merge must happen inside buffer itself, using only a constant amount of extra memory beyond the inputs. Do not build a second list of size a_len + b_len to copy results from.
Modify buffer in place and also return it. The returned list is what gets checked.
Ignore whatever values the placeholder slots hold initially; they carry no meaning and are not part of the data.
Function
Implement merge_into_buffer(buffer, a_len, other, b_len), where:
bufferis a list of integers of lengtha_len + b_len,a_lenis the number of meaningful leading entries inbuffer,otheris a sorted list of integers of lengthb_len,b_lenis the length ofother.
It returns the merged buffer as a list of integers.
Constraints
len(buffer) == a_len + b_lenlen(other) == b_len0 <= a_len, b_len <= 200-10^9 <= buffer[i], other[j] <= 10^9- Both the first
a_lenentries ofbufferand all ofotherare sorted in non-decreasing order.
Edge cases to handle
- Either list may contain no meaningful values (
a_len = 0orb_len = 0). - Every value in
othermay be smaller than every meaningful value inbuffer. - Every value in
othermay be larger than every meaningful value inbuffer. - Duplicate values may appear within and across the lists.
Examples
Example 1
Input: merge_into_buffer([1, 3, 5, 0, 0, 0], 3, [2, 4, 6], 3)
Output: [1, 2, 3, 4, 5, 6]
Example 2
Input: merge_into_buffer([1, 2, 3], 3, [], 0)
Output: [1, 2, 3]
Hints
Hint 1
Filling from the front can overwrite meaningful values of `buffer` that you have not compared yet. Think about which end of `buffer` is guaranteed to be free.
Hint 2
Fill `buffer` from the last position toward the first. At each step the largest remaining value overall is the larger of the two lists' last unplaced elements.
Hint 3
Use three indices: one for the last unplaced meaningful entry of `buffer`, one for the last unplaced entry of `other`, and one write position. You can stop as soon as `other` is exhausted, since the remaining prefix of `buffer` is already in place. Guard against the `buffer` index going below zero.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Merging from the front does not work in place: writing the smaller value into buffer[0] could destroy a meaningful value that has not been compared yet. Shifting to avoid this would cost O(a_len * b_len).
Instead, merge from the back. The last b_len slots of buffer are free, so the largest value of the merged result can be written to the final slot. That value is either the last unplaced meaningful entry of buffer or the last unplaced entry of other.
Keep three indices:
i: the last unplaced meaningful entry inbuffer(starts ata_len - 1),j: the last unplaced entry inother(starts atb_len - 1),write: the next slot to fill (starts ata_len + b_len - 1).
While other still has unplaced values, compare buffer[i] (if i >= 0) with other[j], copy the larger to buffer[write], and move the matching index and write one step left. When other is exhausted, the remaining buffer[0..i] is already sorted and in its final position, so nothing more needs to be done.
Why it is correct
- No unread data is overwritten. The number of free slots to the left of and including
writeequals the number of unplaced values, sowrite = i + j + 1. Whilej >= 0, this meanswrite > i, so writes only hit free slots or values already moved. - Each placement is right. Both inputs are sorted, so the larger of
buffer[i]andother[j]is the largest unplaced value and belongs atwrite. By induction the suffix afterwritealways holds the largest values in order. - Leftovers. If
bufferruns out first (i < 0), the remainingothervalues are copied in. Ifotherruns out first, the remaining prefix ofbufferis already correct. - Guard on
i. Checkingi >= 0prevents Python's negative indexing from reading the end of the list. - Ties. With strict
>, equal values fromotherare placed first at the back, which keeps values frombufferahead of equal ones fromother.
Complexity
- Time: O(a_len + b_len), since each iteration places one value.
- Space: O(1) extra.
Reference solution
from typing import List
def merge_into_buffer(buffer: List[int], a_len: int, other: List[int], b_len: int) -> List[int]:
i, j, write = a_len - 1, b_len - 1, a_len + b_len - 1
while j >= 0:
if i >= 0 and buffer[i] > other[j]:
buffer[write] = buffer[i]
i -= 1
else:
buffer[write] = other[j]
j -= 1
write -= 1
return buffer