KatInterview

Fill a Padded Sorted Buffer from a Second Sorted List

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashingtwo-pointersin-placesorting

Last 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.

  • buffer has length a_len + b_len. Only its first a_len entries are meaningful; the final b_len entries are placeholder slots that can be overwritten freely.
  • other has length b_len and holds b_len meaningful 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:

  • buffer is a list of integers of length a_len + b_len,
  • a_len is the number of meaningful leading entries in buffer,
  • other is a sorted list of integers of length b_len,
  • b_len is the length of other.

It returns the merged buffer as a list of integers.

Constraints

  • len(buffer) == a_len + b_len
  • len(other) == b_len
  • 0 <= a_len, b_len <= 200
  • -10^9 <= buffer[i], other[j] <= 10^9
  • Both the first a_len entries of buffer and all of other are sorted in non-decreasing order.

Edge cases to handle

  • Either list may contain no meaningful values (a_len = 0 or b_len = 0).
  • Every value in other may be smaller than every meaningful value in buffer.
  • Every value in other may be larger than every meaningful value in buffer.
  • 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.