Merge Sorted Arrays
Given two arrays that are already sorted, the goal is to combine them into a single sorted array (or merge one into the other in place) without using extra sorting of the whole combined array.
Two-Pointer Approach
Maintain a pointer for each array. Compare the elements the pointers point to, push the smaller one into the result, and advance that pointer. Continue until one array is exhausted, then append the remainder of the other.
def merge_sorted_arrays(a, b):
i = j = 0
merged = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
merged.append(a[i]); i += 1
else:
merged.append(b[j]); j += 1
merged.extend(a[i:])
merged.extend(b[j:])
return merged
In-Place Variant (LeetCode Style)
When array A has enough trailing empty space to hold array B's elements, merge from the back to avoid overwriting unprocessed values.
Complexity
| Metric | Value |
|---|---|
| Time | O(m + n) |
| Space | O(m + n) or O(1) for in-place |
Applications
- The merge step is the core building block of Merge Sort.
- Merging sorted result sets from distributed/parallel computations.
- Combining sorted log files or streams.
Tracing the Two-Pointer Merge
Merging a = [1, 4, 7] with b = [2, 3, 8] shows how the pointers move. At each step, the smaller front value is copied and its pointer moves forward.
| Step | a[i] | b[j] | Picked | Merged so far |
|---|---|---|---|---|
| 1 | 1 | 2 | 1 | [1] |
| 2 | 4 | 2 | 2 | [1, 2] |
| 3 | 4 | 3 | 3 | [1, 2, 3] |
| 4 | 4 | 8 | 4 | [1, 2, 3, 4] |
| 5 | 7 | 8 | 7 | [1, 2, 3, 4, 7] |
| 6 | a done | 8 | remainder | [1, 2, 3, 4, 7, 8] |
Using <= in the comparison keeps the merge stable: when values are equal, the element from the first array comes first. Merge sort relies on this to stay stable overall.
In-Place Merge from the Back
In the classic interview version, nums1 has length m + n, with its last n slots empty, and nums2 holds n values. Filling from the front would overwrite numbers not yet compared, so we fill from the end, placing the largest remaining value each time.
def merge_in_place(nums1, m, nums2, n):
i, j, k = m - 1, n - 1, m + n - 1
while j >= 0:
if i >= 0 and nums1[i] > nums2[j]:
nums1[k] = nums1[i]
i -= 1
else:
nums1[k] = nums2[j]
j -= 1
k -= 1
nums1 = [1, 2, 3, 0, 0, 0]
merge_in_place(nums1, 3, [2, 5, 6], 3)
print(nums1) # [1, 2, 2, 3, 5, 6]
The loop only runs while nums2 still has values. Once it is empty, whatever remains in nums1 is already in the right place, so no extra copying is needed.
Merging More Than Two Arrays
When you have k sorted lists, comparing all fronts at every step is slow. A min-heap keeps the smallest front value ready, giving roughly O(N log k) time for N total elements.
import heapq
def merge_k(lists):
heap = [(lst[0], idx, 0) for idx, lst in enumerate(lists) if lst]
heapq.heapify(heap)
result = []
while heap:
value, li, pos = heapq.heappop(heap)
result.append(value)
if pos + 1 < len(lists[li]):
heapq.heappush(heap, (lists[li][pos + 1], li, pos + 1))
return result
print(merge_k([[1, 5], [2, 6], [0, 9]])) # [0, 1, 2, 5, 6, 9]
# Python also offers a ready-made lazy version:
print(list(heapq.merge([1, 5], [2, 6], [0, 9])))
The list index in each tuple breaks ties between equal values, which keeps the comparison simple and the output order predictable. Each push and pop costs time proportional to the logarithm of the heap size, and the heap never holds more than one item per input list, so memory stays small even when the lists are long.
Mistakes to Watch For
- Forgetting to copy the leftover elements after one array runs out.
- Merging from the front in the in-place version and overwriting unread values.
- Calling
sorted(a + b)in an interview; it works but costsO((m+n) log(m+n))and misses the point of the question. - Not handling empty inputs, such as
m = 0. - Using
<instead of<=when stability matters, which lets equal items from the second array jump ahead.