KatInterview

Fill Spare Slots and Sort One Buffer In Place

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searcharrayssortingin-place

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

  • a has length m + n. Only its first m entries are real data. The last n entries are filler of arbitrary value (zeros, garbage, or even numbers that look legitimate).
  • b has length n, 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) == n
  • 0 <= m, n <= 10^5, and 1 <= m + n <= 10^5
  • -10^9 <= a[i], b[i] <= 10^9

What to cover in your answer

  1. Your approach and why it is correct, including the edge cases m = 0, n = 0, duplicates, negatives and filler that equals real values.
  2. Time and space complexity, stated honestly (including what the library sort costs in memory).
  3. How the approach changes if a[:m] is already sorted and n is tiny compared with m.
  4. How you would achieve strictly O(1) auxiliary space without a library sort.
  5. 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.