Merge Two Sorted Arrays
Write a function that merges two sorted arrays into a single sorted array.
Advanced
Instructions
Write a function that receives two sorted arrays and merges them into a single sorted array.
For example, if the input arrays are [1,2,3] and [4,5,6], the output should be [1,2,3,4,5,6].
Tests
0/3
Function Call:
Expected:
mergeSortedArrays([1,2,3], [4,5,6])
[
1,
2,
3,
4,
5,
6
]
Run test
mergeSortedArrays([1,1,2,6], [2,7,9])
[
1,
1,
2,
2,
6,
7,
9
]
Run test
Hidden Test
?
Run test
See Solution
Solution
Two-Pointer Approach
const mergeSortedArrays = (array1, array2) => {
let pointer1 = 0
let pointer2 = 0
const result = []
while(pointer1 < array1.length || pointer2 < array2.length){
if(pointer1 < array1.length){
if(pointer2 < array2.length){
if(array1[pointer1] < array2[pointer2]){
result.push(array1[pointer1])
pointer1 += 1
} else {
result.push(array2[pointer2])
pointer2 += 1
}
} else {
result.push(array1[pointer1])
pointer1 += 1
}
} else {
result.push(array2[pointer2])
pointer2 += 1
}
}
return result
}
Explanation
- The function
mergeSortedArrays
takes two sorted arrays as input. - It initializes two pointers,
pointer1
andpointer2
, to keep track of the current index in each array. - It then initializes an empty array
result
to store the merged sorted array. - The function uses a while loop to iterate over the arrays until both pointers reach the end of their respective arrays.
- It compares the elements at the current indices of the two arrays and pushes the smaller element into the
result
array. - It then increments the pointer of the array from which the element was pushed.
- If one of the arrays has been fully traversed, the function pushes the remaining elements of the other array into the
result
array. - Finally, it returns the merged sorted array.
Concatenate and Sort
const mergeSortedArrays = (array1, array2) => {
return array1.concat(array2).sort((a, b) => a - b);
}
Explanation
- The function
mergeSortedArrays
takes two arrays as input. - It concatenates the two arrays using the
concat
method. - It then sorts the concatenated array using the
sort
method with a comparator function that compares two elementsa
andb
and returns a negative value ifa
should come beforeb
, a positive value ifa
should come afterb
, and zero if they are equal.
Complexity Analysis
The time complexity for this solution is O((n+m)log(n+m)), where n and m are the lengths of the two input arrays.
This is because the sort
method has a time complexity of O(nlogn), where n is the length of the array.
Any improvement idea? Share with us!