Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Merge Sorted Array in Python
When working with two sorted arrays, we often need to merge them into a single sorted array. Python provides several approaches to accomplish this task efficiently.
For example, if we have A = [1,2,4,7] and B = [1,3,4,5,6,8], the merged result should be [1,1,2,3,4,4,5,6,7,8].
Using Two Pointers Approach
The most efficient approach uses two pointers to compare elements from both arrays ?
def merge_sorted_arrays(arr1, arr2):
merged = []
i = j = 0
# Compare elements and add smaller one to result
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
merged.append(arr1[i])
i += 1
else:
merged.append(arr2[j])
j += 1
# Add remaining elements
merged.extend(arr1[i:])
merged.extend(arr2[j:])
return merged
# Example usage
A = [1, 2, 4, 7]
B = [1, 3, 4, 5, 6, 8]
result = merge_sorted_arrays(A, B)
print("Merged array:", result)
Merged array: [1, 1, 2, 3, 4, 4, 5, 6, 7, 8]
In-Place Merge (LeetCode Style)
When merging into an existing array with extra space, we can use backward iteration ?
def merge_in_place(nums1, m, nums2, n):
"""
Merge nums2 into nums1 in-place
nums1 has size m + n with extra zeros
"""
i = m - 1 # Last element in nums1
j = n - 1 # Last element in nums2
k = m + n - 1 # Last position in nums1
# Merge from the end
while i >= 0 and j >= 0:
if nums1[i] > nums2[j]:
nums1[k] = nums1[i]
i -= 1
else:
nums1[k] = nums2[j]
j -= 1
k -= 1
# Add remaining elements from nums2
while j >= 0:
nums1[k] = nums2[j]
j -= 1
k -= 1
return nums1
# Example usage
nums1 = [1, 2, 3, 0, 0, 0] # m = 3, extra space for 3 elements
nums2 = [2, 5, 6] # n = 3
result = merge_in_place(nums1, 3, nums2, 3)
print("Merged in-place:", result)
Merged in-place: [1, 2, 2, 3, 5, 6]
Using Built-in Functions
Python's built-in functions provide a simple solution ?
def merge_using_builtin(arr1, arr2):
# Method 1: Using sorted()
combined = arr1 + arr2
return sorted(combined)
def merge_using_heapq(arr1, arr2):
# Method 2: Using heapq.merge()
import heapq
return list(heapq.merge(arr1, arr2))
# Example usage
A = [1, 2, 4, 7]
B = [1, 3, 4, 5, 6, 8]
result1 = merge_using_builtin(A, B)
print("Using sorted():", result1)
result2 = merge_using_heapq(A, B)
print("Using heapq.merge():", result2)
Using sorted(): [1, 1, 2, 3, 4, 4, 5, 6, 7, 8] Using heapq.merge(): [1, 1, 2, 3, 4, 4, 5, 6, 7, 8]
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Two Pointers | O(m + n) | O(m + n) | General merging |
| In-place | O(m + n) | O(1) | Memory constraints |
| Built-in sorted() | O((m+n)log(m+n)) | O(m + n) | Simple implementation |
| heapq.merge() | O(m + n) | O(1) iterator | Memory-efficient |
Conclusion
Use the two pointers approach for optimal time complexity. For in-place merging with space constraints, use backward iteration. The heapq.merge() function is ideal when working with large datasets due to its iterator-based approach.
