Introduction
The Merge Sorted Arrays problem involves combining two sorted arrays into a single sorted array.
Given two sorted arrays:
- arr1[ ]
- arr2[ ]
the task is to merge them while maintaining sorted order.
This problem helps in understanding:
- Two Pointer Technique
- sorted traversal
- merging logic
- efficient array processing
This concept is heavily used in:
Merge Sort AlgorithmExample
Input:arr1[] = [1,3,5]
arr2[] = [2,4,6]
Output:
[1,2,3,4,5,6]
Explanation:
Elements from both arrays are merged
while maintaining sorted order.
Input:
arr1[] = [1,2,7]
arr2[] = [3,4,5]
Output:
[1,2,3,4,5,7]
Explanation:
Merged array remains sorted.
Constraints
1 <= n,m <= 10^5-10^9 <= arr[i] <= 10^9Arrays are sorted
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Combine both arrays
- Sort the final array
This approach is easy to understand but sorting increases time complexity.
Steps
- Create a new array.
- Insert elements from first array.
- Insert elements from second array.
- Sort final array.
- Return merged array.
Dry Run
Input:arr1 = [1,3,5]
arr2 = [2,4,6]
Combine arrays:
[1,3,5,2,4,6]
Sort combined array:
[1,2,3,4,5,6]
Final Result:
[1,2,3,4,5,6]
Brute Force Code
Complexity Analysis
Time Complexity: O((n + m) log(n + m))Explanation:
Combined array is sorted.
Space Complexity: O(n + m)
Explanation:
Extra merged array is used.
Approach 2 : Optimized Solution (Two Pointer Technique)
Explanation
Since both arrays are already sorted, we can efficiently merge them using two pointers.
The idea is:
- Compare current elements of both arrays
- Insert smaller element into result
- Move corresponding pointer
This avoids unnecessary sorting.
Steps
- Initialize:
- pointer i for arr1
- pointer j for arr2
- Compare current elements.
- Insert smaller element into merged array.
- Move corresponding pointer.
- Insert remaining elements after traversal.
Dry Run
Input:arr1 = [1,3,5]
arr2 = [2,4,6]
Initially:
i = 0
j = 0
Compare:
1 and 2
1 is smaller
Merged:
[1]
Move i
Compare:
3 and 2
2 is smaller
Merged:
[1,2]
Move j
Continue traversal...
Final Result:
[1,2,3,4,5,6]
Optimized Code
Complexity Analysis
Time Complexity: O(n + m)Explanation: Both arrays are traversed once.
Space Complexity: O(n + m)
Explanation:
Extra merged array is used.