KatInterview

Merge Two Sorted Lists Into a Padded Buffer

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashingtwo-pointersin-placesorted-arrays

Last 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 nums list 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, nums is returned with its first m entries unchanged.
  • If m == 0, the n elements of extra are copied into nums in order.
  • All of extra may be smaller than all of nums, 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.