In-Place Merge and Sort of Two Unsorted Arrays

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given two unsorted integer lists a and b together with integer counts m and n, combine their active values into a in non-decreasing order in place:

  • List a has pre-allocated length m + n. Its first m positions (a[0 : m]) store active unsorted integers, while its trailing n positions (a[m : m + n]) are unused capacity slots filled with arbitrary integers (zeros, negative numbers, duplicates, or arbitrary filler values).
  • List b has length n (b[0 : n]) and stores n active unsorted integers.

Implement merge_and_sort so that a itself ends up holding all m + n active integers sorted from smallest to largest, returning None and leaving b unmodified:

from typing import List


def merge_and_sort(a: List[int], m: int, b: List[int], n: int) -> None:
    ...

Examples

Example 1

Input:  a = [12, 4, 7, 99, 99], m = 3, b = [1, 7], n = 2
Output: a becomes [1, 4, 7, 7, 12]

Explanation: Only a[:3] = [12, 4, 7] are active values; the two 99 entries at a[3:5] are unused buffer slots. Writing b = [1, 7] into a[3:5] yields [12, 4, 7, 1, 7], and sorting a in place produces [1, 4, 7, 7, 12].

Example 2

Input:  a = [0, -4, 6, 0, 0], m = 3, b = [-2, 0], n = 2
Output: a becomes [-4, -2, 0, 0, 6]

Explanation: 0 is a legitimate value at a[0] and b[1] as well as a filler value in a[3:5]. Using m = 3 as the exact boundary overwrites a[3] and a[4] with -2 and 0 to give [0, -4, 6, -2, 0], which sorts in place to [-4, -2, 0, 0, 6].

Constraints

  • len(a) == m + n
  • len(b) == n
  • 0 <= m, n <= 10^5
  • 1 <= m + n <= 10^5
  • -10^9 <= a[i], b[i] <= 10^9
  • Mutate the list object a in place and return None; do not mutate b.

Step-by-step walkthrough

  1. Understand the input layout and in-place contract

    Look closely at how array a is structured before our function runs:

    Index:     0       1     ...    m - 1      m      m + 1   ...   m + n - 1
             +-------+-------+-----+-------+--------+--------+-----+-----------+
    Array a: | valid | valid | ... | valid | unused | unused | ... |  unused   |
             +-------+-------+-----+-------+--------+--------+-----+-----------+
             |<------- m real items ------>|<----- n placeholder slots ------->|
    
    • a[0 : m] holds m unsorted valid integers.
    • a[m : m + n] holds n pre-allocated placeholder slots whose current values are meaningless garbage.
    • b[0 : n] holds n unsorted valid integers (and b itself should not be modified).
    • In-place requirement: The function returns None. Callers check the exact same list object a they passed in, so writing a = sorted(...) inside the function fails because = only points the local variable a at a brand-new list while leaving the caller's list untouched.

    Because neither a[:m] nor b is sorted initially, we cannot simply run a linear two-pointer merge — sorting the combined values is unavoidable.

  2. Why you must trust m instead of scanning for zeros

    A common beginner trap is scanning a to look for the first 0 to find where valid elements end. Example 2 shows why that breaks immediately:

    a = [0, -4, 6, 0, 0],  m = 3
    b = [-2, 0],           n = 2
    

    Here 0 appears as a real data value in a[0] and b[1], and as a garbage placeholder in a[3] and a[4] (or a placeholder can be 99 as in Example 1 instead of 0).

    The count m tells us the exact boundary: valid data occupies indices 0 through m - 1, and free slots start at index m. For each index i from 0 to n - 1, b[i] belongs at a[m + i].

  3. Naive slice copy vs. filling the reserved tail directly

    One short way to mutate a is slice assignment:

    def merge_and_sort_slice(a: list, m: int, b: list, n: int) -> None:
        # Builds `a[:m] + b` (a new list of m + n items) and `sorted(...)` (a second new list).
        a[:] = sorted(a[:m] + b)
    

    While a[:] = ... does mutate the caller's list object, a[:m] + b allocates an unnecessary temporary array of size m + n even though a already reserved n empty slots at the end!

    Instead, write each b[i] directly into a[m + i], then sort a in place with a.sort():

    from typing import List
    
    
    def merge_and_sort(a: List[int], m: int, b: List[int], n: int) -> None:
        # `a` has length m + n: [valid_0, ..., valid_{m-1}, placeholder_0, ..., placeholder_{n-1}].
        # Phase 1: Overwrite the n reserved tail slots by index (never check for 0, since 0 can be valid data).
        for i in range(n):
            target_index = m + i
            a[target_index] = b[i]
    
        # Phase 2: Sort `a` in place (Timsort) so the caller's own list object is mutated.
        a.sort()
    
  4. Compare copy-then-sort against sort-both-then-merge

    A natural design question is: what if we sorted a[:m] first, sorted b second, and then merged them from the back of a using three pointers? Let N = m + n and compare total work:

    Strategy                       Work breakdown                 Asymptotic time
    -----------------------------  -----------------------------  ---------------
    1. Copy b into tail + sort a   n  +  N log2(N)                Theta(N log N)
    2. Sort a[:m], sort b, merge   m log2(m) + n log2(n) + N      Theta(N log N)
    

    Why is Strategy 2 not asymptotically faster than Strategy 1? Because m + n = N, whichever side is larger has size max(m, n) >= N / 2. Sorting just that larger half already requires at least (N / 2) log2(N / 2) comparisons, which grows at the exact same Theta(N log N) rate as N log2(N)! Strategy 1 is much simpler, avoids mutating or copying b, and has zero pointer-boundary bugs. (As we will see in the follow-ups, the three-pointer merge shines when a[:m] is already sorted.)

  5. Step-by-step trace on both examples

    Trace Example 1: a = [12, 4, 7, 99, 99], m = 3, b = [1, 7], n = 2:

    Initial a:              [12, 4, 7, 99, 99]
    i = 0 -> a[3 + 0] = 1:  [12, 4, 7, 1, 99]
    i = 1 -> a[3 + 1] = 7:  [12, 4, 7, 1, 7]
    After a.sort():         [1, 4, 7, 7, 12]
    

    Trace Example 2: a = [0, -4, 6, 0, 0], m = 3, b = [-2, 0], n = 2:

    Initial a:              [0, -4, 6, 0, 0]
    i = 0 -> a[3 + 0] = -2: [0, -4, 6, -2, 0]
    i = 1 -> a[3 + 1] = 0:  [0, -4, 6, -2, 0]   (placeholder 0 overwritten by real 0 from b[1])
    After a.sort():         [-4, -2, 0, 0, 6]
    

    Boundary values of m and n work automatically with zero special if branches: - When m = 0, target_index = 0 + i = i, so the loop copies all of b into a[0 : n] and sorts a. - When n = 0, range(0) is empty, so the loop does nothing and a.sort() sorts a[0 : m].

  6. Complete solution

    from typing import List
    
    
    def merge_and_sort(a: List[int], m: int, b: List[int], n: int) -> None:
        # `a` has length m + n: [valid_0, ..., valid_{m-1}, placeholder_0, ..., placeholder_{n-1}].
        # Phase 1: Overwrite the n reserved tail slots by index (never check for 0, since 0 can be valid data).
        for i in range(n):
            target_index = m + i
            a[target_index] = b[i]
    
        # Phase 2: Sort `a` in place (Timsort) so the caller's own list object is mutated.
        a.sort()
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of array a like a bookshelf with m + n slots where the first m slots hold unsorted books and the last n slots hold cardboard spacers, while box b holds n more unsorted books. Instead of buying a brand-new bookshelf, you pull out the n cardboard spacers starting at slot m, slide the n books from box b straight into those slots, and then alphabetize the single shelf from left to right (in-place mutation — modifying the existing array object directly rather than returning a new array).

Why do naive shortcuts fail? First, looking for 0 as a sentinel (a special marker value assumed to mean "empty") breaks whenever 0 is a legitimate number in a or b, or when unused slots contain non-zero garbage like -99. Second, calling a.extend(b) glues b after the placeholders, leaving m + 2n elements with garbage mixed in. Third, writing a = sorted(a[:m] + b) inside the function only reassigns the local variable a, leaving the caller's list completely unchanged.

Walk through a concrete 5-element trace with a = [0, -4, 6, 0, 0], m = 3, b = [-2, 0], n = 2: 1. Slot m + 0 = 3 receives b[0] = -2 -> a is [0, -4, 6, -2, 0]. 2. Slot m + 1 = 4 receives b[1] = 0 -> a is [0, -4, 6, -2, 0] (now both 0s are real data!). 3. a.sort() sorts a in place using Python's Timsort (a hybrid merge-and-insertion sort built into Python) -> a becomes [-4, -2, 0, 0, 6], while b remains [-2, 0].

Complexity

Let N = m + n be the total length of a:

  • Time complexity: O(N log N) (O((m + n) log(m + n))). We copy n elements into a[m : m + n] in a single O(n) loop, and then a.sort() orders all N elements in O(N log N) comparisons in the worst case. Because the input elements are arbitrary unsorted integers, any comparison-based sort requires at least Omega(N log N) comparisons in the worst case.
  • Auxiliary space complexity: O(N) in Python (or O(1) with heapsort). Auxiliary space is the extra temporary memory allocated beyond the inputs themselves. Our copy loop uses O(1) extra memory (just loop variable i), but Python's list.sort() (Timsort) allocates a temporary merge buffer holding up to N // 2 object references (O(N) space) to merge sorted runs stably. If strict O(1) auxiliary space is required, replacing a.sort() with an iterative heapsort (an in-place sorting algorithm that turns the array itself into a binary max-heap) achieves O(N log N) time and O(1) extra memory.

Edge cases

  • m = 0 (a is all placeholders): target_index runs across 0 .. n - 1, overwriting every placeholder with b before sorting.
  • n = 0 (b is empty): The copy loop executes zero iterations and a.sort() simply sorts the m elements of a.
  • Single element (m + n = 1): Either (m=1, n=0) or (m=0, n=1) leaves the single valid integer in a[0].
  • Zeros and extreme integers (-10^9, 10^9) as both data and placeholders: Because a[m : m + n] is overwritten strictly by index without ever inspecting its old values, garbage values can never leak into the output.
  • Duplicates and negative values: Preserved in non-decreasing order ([-1, -1, -1]).

Common mistakes

  • Scanning for 0 to locate the end of a's valid prefix: Breaks whenever 0 is a valid element inside a[:m] or when placeholders contain non-zero values.
  • Rebinding the local parameter (a = sorted(...)): Mutates what the local name a points to inside the function frame, so the caller still sees the original unsorted list.
  • Using a.extend(b) or a += b: Appends b at index m + n instead of index m, growing a to length m + 2n and sorting the garbage placeholders into the result.
  • Sorting a slice (a[:m + n].sort()): In Python, slicing a list (a[...]) creates a shallow copy, so .sort() sorts the temporary copy and immediately discards it!
  • Sorting b in place (b.sort()): Unexpectedly mutates the caller's second input array.

Alternative approaches

  • Slice assignment (a[:] = sorted(a[:m] + b)): Clean one-liner that properly mutates a in O(N log N) time, but allocates two full O(N) intermediate lists (a[:m] + b and the sorted result) before copying back into a.
  • Sort both halves, then three-pointer merge from the back: Sort a[:m], create a sorted copy of b, and merge from index m + n - 1 down to 0 by repeatedly picking the larger tail element. Writing from right to left guarantees the write pointer never overtakes the unread prefix of a[:m]. Total work is O(m log m + n log n + N), which is still Theta(N log N) when both inputs start unsorted, so copy-then-sort is cleaner unless a[:m] is already sorted.

Follow-up questions

  • How do the time and extra-memory complexities compare between copying b into the tail of a and running Timsort or Quicksort versus sorting both inputs separately and merging them? Copying b into a plus Timsort takes O(N log N) worst-case time and O(N) worst-case auxiliary space (for Timsort's merge buffer, up to N / 2 pointers). Copying b into a plus in-place Quicksort (with randomized or median-of-three pivots and tail-recursing on the larger partition) takes O(N log N) average time, O(N^2) worst-case time, and O(log N) auxiliary call-stack space. Sorting the two subarrays separately and merging from the back performs m log m + n log n + N operations — slightly fewer comparisons by a constant additive term when m ≈ n, yet still Theta(N log N) asymptotically because max(m, n) >= N / 2 — and requires O(n) extra space if you avoid mutating b plus whatever auxiliary space the subarray sort uses.
  • Suppose m is huge while n is tiny (for instance, m = 1,000,000 and n = 4). What is the best strategy for incorporating b into a, and how does the answer change if a[:m] is already sorted? Separate the two cases. When a[:m] is unsorted (as stated in the base problem), sorting those 10^6 arbitrary elements requires Omega(m log m) comparisons no matter how we insert b, so copying the 4 items to a[m : m + 4] and calling a.sort() in O((m + n) log(m + n)) = O(m log m) is already asymptotically optimal. When a[:m] is already sorted (common when appending small batches to an ordered buffer), sort the n = 4 items of b in O(n log n) (tiny constant work) and run a back-to-front two-pointer merge from k = m + n - 1 downward, stopping the loop the instant all 4 items of b are placed — which takes O(m + n) worst-case element shifts (and only O(n log m) comparisons if you locate split positions with binary search) and O(n) extra space. (Notably, Python's Timsort also detects a pre-sorted a[:m] run automatically in m - 1 comparisons and merges the 4-item run via binary-search galloping in O(m + n) time!)
  • If built-in sorting routines were disallowed and you had to guarantee strict O(1) auxiliary memory, what algorithm would you implement? First copy b into a[m : m + n] using O(1) loop variables, and then run iterative in-place heapsort across a[0 : m + n]. Phase 1 (heapify) sifts every non-leaf index from (N // 2) - 1 down to 0 to turn a into a max-heap (a binary tree stored directly in the array where every parent at index i is >= its children at 2i + 1 and 2i + 2) in O(N) time. Phase 2 repeatedly swaps the maximum element at a[0] with the last unsorted position end (from N - 1 down to 1) and sifts the new root down within a[0 : end] in O(log N) per step — guaranteeing O(N log N) worst-case time and strictly O(1) extra variables (i, root, child, end), with zero recursion stack or merge buffers.

Follow-up questions

Similar questions

More Fora Travel interview questions

All 7 Fora Travel questions →