Merge Two Sorted Arrays Without Extra Space in Python
Merge two sorted arrays in-place from the end, using the trailing zeros in the first array to avoid extra space.
Python code
18 linesdef merge_sorted(arr1, arr2):
m, n = len(arr1), len(arr2)
i, j = m - 1, n - 1
while j >= 0:
if i >= 0 and arr1[i] > arr2[j]:
arr1[i + j + 1] = arr1[i]
i -= 1
else:
arr1[i + j + 1] = arr2[j]
j -= 1
return arr1
if __name__ == "__main__":
arr1 = [1, 3, 5, 7, 0, 0, 0]
arr2 = [2, 4, 6]
merged = merge_sorted(arr1, arr2)
print(merged)
Output
[1, 2, 3, 4, 5, 6, 7]
How it works
The algorithm starts from the back of both arrays, comparing the largest remaining elements and placing the larger one at the end of the merged region. The index for the placement is calculated as i + j + 1, which accounts for the current positions in both arrays. This approach works because the first array has enough trailing zeros to hold all elements of the second array. The time complexity is O(m+n) and the space complexity is O(1).
Common mistakes
- Forgetting to account for the trailing zeros when calculating the placement index
- Not handling the case where one array is exhausted correctly
- Using a naive merge that overwrites values before they are read
Variations
- Use a similar back-to-front approach when merging two sorted linked lists in-place
- Implement the same logic as a LeetCode-style solution for 'Merge Sorted Array'
Real-world use cases
- Merging two sorted time-series data streams into a single time-ordered array without allocating a new buffer.
- Combining sorted log entries from two sources directly into a fixed-size output array in memory-constrained systems.
- Implementing an in-place merge as part of a custom sorting algorithm like merge sort for large arrays on limited hardware.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.