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
ahas pre-allocated lengthm + n. Its firstmpositions (a[0 : m]) store active unsorted integers, while its trailingnpositions (a[m : m + n]) are unused capacity slots filled with arbitrary integers (zeros, negative numbers, duplicates, or arbitrary filler values). - List
bhas lengthn(b[0 : n]) and storesnactive 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 + nlen(b) == n0 <= m, n <= 10^51 <= m + n <= 10^5-10^9 <= a[i], b[i] <= 10^9- Mutate the list object
ain place and returnNone; do not mutateb.
Step-by-step walkthrough
Understand the input layout and in-place contract
Look closely at how array
ais 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]holdsmunsorted valid integers.a[m : m + n]holdsnpre-allocated placeholder slots whose current values are meaningless garbage.b[0 : n]holdsnunsorted valid integers (andbitself should not be modified).- In-place requirement: The function returns
None. Callers check the exact same list objectathey passed in, so writinga = sorted(...)inside the function fails because=only points the local variableaat a brand-new list while leaving the caller's list untouched.
Because neither
a[:m]norbis sorted initially, we cannot simply run a linear two-pointer merge — sorting the combined values is unavoidable.Why you must trust m instead of scanning for zeros
A common beginner trap is scanning
ato look for the first0to find where valid elements end. Example 2 shows why that breaks immediately:a = [0, -4, 6, 0, 0], m = 3 b = [-2, 0], n = 2Here
0appears as a real data value ina[0]andb[1], and as a garbage placeholder ina[3]anda[4](or a placeholder can be99as in Example 1 instead of0).The count
mtells us the exact boundary: valid data occupies indices0throughm - 1, and free slots start at indexm. For each indexifrom0ton - 1,b[i]belongs ata[m + i].Naive slice copy vs. filling the reserved tail directly
One short way to mutate
ais 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] + ballocates an unnecessary temporary array of sizem + neven thoughaalready reservednempty slots at the end!Instead, write each
b[i]directly intoa[m + i], then sortain place witha.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()Compare copy-then-sort against sort-both-then-merge
A natural design question is: what if we sorted
a[:m]first, sortedbsecond, and then merged them from the back ofausing three pointers? LetN = m + nand 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 sizemax(m, n) >= N / 2. Sorting just that larger half already requires at least(N / 2) log2(N / 2)comparisons, which grows at the exact sameTheta(N log N)rate asN log2(N)! Strategy 1 is much simpler, avoids mutating or copyingb, and has zero pointer-boundary bugs. (As we will see in the follow-ups, the three-pointer merge shines whena[:m]is already sorted.)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
mandnwork automatically with zero specialifbranches: - Whenm = 0,target_index = 0 + i = i, so the loop copies all ofbintoa[0 : n]and sortsa. - Whenn = 0,range(0)is empty, so the loop does nothing anda.sort()sortsa[0 : m].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 copynelements intoa[m : m + n]in a singleO(n)loop, and thena.sort()orders allNelements inO(N log N)comparisons in the worst case. Because the input elements are arbitrary unsorted integers, any comparison-based sort requires at leastOmega(N log N)comparisons in the worst case. - Auxiliary space complexity:
O(N)in Python (orO(1)with heapsort). Auxiliary space is the extra temporary memory allocated beyond the inputs themselves. Our copy loop usesO(1)extra memory (just loop variablei), but Python'slist.sort()(Timsort) allocates a temporary merge buffer holding up toN // 2object references (O(N)space) to merge sorted runs stably. If strictO(1)auxiliary space is required, replacinga.sort()with an iterative heapsort (an in-place sorting algorithm that turns the array itself into a binary max-heap) achievesO(N log N)time andO(1)extra memory.
Edge cases
m = 0(ais all placeholders):target_indexruns across0 .. n - 1, overwriting every placeholder withbbefore sorting.n = 0(bis empty): The copy loop executes zero iterations anda.sort()simply sorts themelements ofa.- Single element (
m + n = 1): Either(m=1, n=0)or(m=0, n=1)leaves the single valid integer ina[0]. - Zeros and extreme integers (
-10^9,10^9) as both data and placeholders: Becausea[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
0to locate the end ofa's valid prefix: Breaks whenever0is a valid element insidea[:m]or when placeholders contain non-zero values. - Rebinding the local parameter (
a = sorted(...)): Mutates what the local nameapoints to inside the function frame, so the caller still sees the original unsorted list. - Using
a.extend(b)ora += b: Appendsbat indexm + ninstead of indexm, growingato lengthm + 2nand 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
bin 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 mutatesainO(N log N)time, but allocates two fullO(N)intermediate lists (a[:m] + band the sorted result) before copying back intoa. - Sort both halves, then three-pointer merge from the back: Sort
a[:m], create a sorted copy ofb, and merge from indexm + n - 1down to0by repeatedly picking the larger tail element. Writing from right to left guarantees the write pointer never overtakes the unread prefix ofa[:m]. Total work isO(m log m + n log n + N), which is stillTheta(N log N)when both inputs start unsorted, so copy-then-sort is cleaner unlessa[: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
bintoaplus Timsort takesO(N log N)worst-case time andO(N)worst-case auxiliary space (for Timsort's merge buffer, up toN / 2pointers). Copyingbintoaplus in-place Quicksort (with randomized or median-of-three pivots and tail-recursing on the larger partition) takesO(N log N)average time,O(N^2)worst-case time, andO(log N)auxiliary call-stack space. Sorting the two subarrays separately and merging from the back performsm log m + n log n + Noperations — slightly fewer comparisons by a constant additive term whenm ≈ n, yet stillTheta(N log N)asymptotically becausemax(m, n) >= N / 2— and requiresO(n)extra space if you avoid mutatingbplus 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 those10^6arbitrary elements requiresOmega(m log m)comparisons no matter how we insertb, so copying the 4 items toa[m : m + 4]and callinga.sort()inO((m + n) log(m + n)) = O(m log m)is already asymptotically optimal. Whena[:m]is already sorted (common when appending small batches to an ordered buffer), sort then = 4items ofbinO(n log n)(tiny constant work) and run a back-to-front two-pointer merge fromk = m + n - 1downward, stopping the loop the instant all 4 items ofbare placed — which takesO(m + n)worst-case element shifts (and onlyO(n log m)comparisons if you locate split positions with binary search) andO(n)extra space. (Notably, Python's Timsort also detects a pre-sorteda[:m]run automatically inm - 1comparisons and merges the 4-item run via binary-search galloping inO(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
bintoa[m : m + n]usingO(1)loop variables, and then run iterative in-place heapsort acrossa[0 : m + n]. Phase 1 (heapify) sifts every non-leaf index from(N // 2) - 1down to0to turnainto a max-heap (a binary tree stored directly in the array where every parent at indexiis>=its children at2i + 1and2i + 2) inO(N)time. Phase 2 repeatedly swaps the maximum element ata[0]with the last unsorted positionend(fromN - 1down to1) and sifts the new root down withina[0 : end]inO(log N)per step — guaranteeingO(N log N)worst-case time and strictlyO(1)extra variables (i,root,child,end), with zero recursion stack or merge buffers.
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?
- 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?
- If built-in sorting routines were disallowed and you had to guarantee strict O(1) auxiliary memory, what algorithm would you implement?
Similar questions
- Merge Sorted Arrays
- Curriculum Hierarchy API and Versioned Caching
- Design a Read-Cached Inventory System for Hotel Reservations
- Hierarchical Learning Progress APIs and Data Model
- Design a Multi-Channel Emergency Alerting System
- Real-Time Proximity Push Service for Mobile Devices
More Fora Travel interview questions
- Hierarchical Learning Progress APIs and Data Model Medium
- Real-Time Proximity Push Service for Mobile Devices Medium
- Design a Read-Cached Inventory System for Hotel Reservations Easy Pro
- Design a Multi-Channel Emergency Alerting System Medium Pro
- Curriculum Hierarchy API and Versioned Caching Easy Pro
- Merge Sorted Arrays Medium Pro