![]() |
VOOZH | about |
Given two sorted arrays arr1[] of size n and arr2[] of size m. Merge these two arrays.
After the merge, the first n smallest elements of the combined sorted array should be stored in arr1[], and the remaining m largest elements should be stored in arr2[]. After the merging process, both arr1[] and arr2[] must remain sorted in non-decreasing order.
Examples:
Input: arr1[] = [1, 3, 4, 5], arr2[] = [2, 4, 6, 8]
Output: arr1[] = [1, 2, 3, 4], arr2[] = [4 5, 6, 8]
Explanation: Combined sorted array = [1, 2, 3, 4, 4, 5, 6, 8], array arr1[] contains smallest 4 elements: 1, 2, 3, 4, and array arr2[] contains the remaining 4 elements: 4, 5, 6, 8.Input: arr1[] = [5, 8, 9], arr2[] = [4, 7, 8]
Output: arr1[] = [4, 5, 7], arr2[] = [8, 8, 9]
Explanation: Combined sorted array = [4, 5, 7, 8, 8, 9], array arr1[] contains smallest 3 elements: 4, 5, 7, and array arr2[] contains the remaining 3 elements: 8, 8, 9.
Table of Content
The idea is to combine both sorted arrays into a single temporary array, then sort this combined array to get all elements in non-decreasing order. Once sorted, the first n smallest elements are copied back into arr1, and the remaining m largest elements are placed into arr2.
1 2 3 4 5 6 7 8
The idea is to use the two-pointer to merge both sorted arrays into a temporary array in linear time. We compare elements from arr1 and arr2 one by one and append the smaller element to the merged array. After merging, we copy the first n elements back to arr1 and the remaining m elements to arr2.
Step-by-Step Implementation:
1 2 3 4 5 6 7 8
Merge two sorted arrays with O(1) extra space
Merge k sorted arrays
Union of Two Sorted Arrays
Intersection of Two Sorted Arrays
Merge 2 sorted linked list in reverse order
Sort last M elements
Merge 2 sorted linked list in reverse order
Merge Sort for Doubly Linked List