Merge Sorted Arrays
easySave
ArraySortingTwo Pointers
Given two sorted arrays, the task is to merge these arrays such that the final formed array is sorted. You should not use any extra space (i.e., modify the input arrays in-place).
Example 1
Input
[ [ 1, 3, 5, 0, 0, 0 ], [ 2, 4, 6 ] ]
Output
[1, 2, 3, 4, 5, 6]
Explanation. The zeros in the first array are placeholders to accommodate the elements from the second array.
Example 2
Input
[ [ 7, 8, 9, 0, 0, 0 ], [ 1, 2, 3 ] ]
Output
[1, 2, 3, 7, 8, 9]
Explanation. The merged array should fit all elements in sorted order.
Example 3
Input
[ [ -1, 3, 5 ], [ -2, 4, 6 ] ]
Output
[-2, -1, 3, 4, 5, 6]
Explanation. Make sure to handle arrays with negative integers correctly.
Follow-up: Try to optimize the approach as much as possible, aiming for a time complexity less than O(nlogn).
Constraints:
- The arrays may be of different sizes. - The elements of the arrays are integers. - No integer will appear more than twice across both arrays.
- Views
- 2