Given two sorted arrays of integers, merge them into one sorted array containing all numbers
Example:
Input: first =[1, 4, 8], second = [1, 3, 4, 17] Output: [1, 1, 3, 4, 4, 8, 17]
Your algorithm should run in O(n + m) time and use O(n + m) extra space.
The core challenge of this problem is to merge two already sorted arrays into a single sorted array efficiently. This problem is significant in various applications such as merging data from different sources, combining search results, and in algorithms like merge sort.
Potential pitfalls include not maintaining the sorted order or using inefficient methods that exceed the desired time complexity.
To solve this problem, we can use a two-pointer technique. This approach is efficient and ensures that we maintain the sorted order while merging the arrays.
Here’s a step-by-step approach:
Let's break down the algorithm step-by-step:
i
and j
, to 0.merged
to store the result.first[i]
and second[j]
.merged
.merged
.def merge_sorted_arrays(first, second):
# Initialize pointers for both arrays
i, j = 0, 0
merged = []
# Traverse both arrays
while i < len(first) and j < len(second):
if first[i] < second[j]:
merged.append(first[i])
i += 1
else:
merged.append(second[j])
j += 1
# If there are remaining elements in the first array
while i < len(first):
merged.append(first[i])
i += 1
# If there are remaining elements in the second array
while j < len(second):
merged.append(second[j])
j += 1
return merged
# Example usage
first = [1, 4, 8]
second = [1, 3, 4, 17]
print(merge_sorted_arrays(first, second)) # Output: [1, 1, 3, 4, 4, 8, 17]
The time complexity of this approach is O(n + m) because we traverse each array once. The space complexity is also O(n + m) due to the additional space required for the merged array.
Consider the following edge cases:
Our algorithm handles these cases effectively by ensuring all elements are considered and merged appropriately.
To test the solution comprehensively, consider the following test cases:
def test_merge_sorted_arrays():
assert merge_sorted_arrays([], []) == []
assert merge_sorted_arrays([1], []) == [1]
assert merge_sorted_arrays([], [1]) == [1]
assert merge_sorted_arrays([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6]
assert merge_sorted_arrays([1, 2, 3], [4, 5, 6]) == [1, 2, 3, 4, 5, 6]
assert merge_sorted_arrays([4, 5, 6], [1, 2, 3]) == [1, 2, 3, 4, 5, 6]
assert merge_sorted_arrays([1, 4, 8], [1, 3, 4, 17]) == [1, 1, 3, 4, 4, 8, 17]
test_merge_sorted_arrays()
print("All tests passed.")
When approaching such problems, consider the following tips:
In this blog post, we discussed how to merge two sorted arrays efficiently using a two-pointer technique. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for improving your algorithmic thinking and coding skills.
For further reading and practice, consider the following resources: