Login

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

  1. The function mergeSortedArrays takes two sorted arrays as input.
  2. It initializes two pointers, pointer1 and pointer2, to keep track of the current index in each array.
  3. It then initializes an empty array result to store the merged sorted array.
  4. The function uses a while loop to iterate over the arrays until both pointers reach the end of their respective arrays.
  5. It compares the elements at the current indices of the two arrays and pushes the smaller element into the result array.
  6. It then increments the pointer of the array from which the element was pushed.
  7. If one of the arrays has been fully traversed, the function pushes the remaining elements of the other array into the result array.
  8. Finally, it returns the merged sorted array.

Concatenate and Sort

const mergeSortedArrays = (array1, array2) => {
    return array1.concat(array2).sort((a, b) => a - b);
}

Explanation

  1. The function mergeSortedArrays takes two arrays as input.
  2. It concatenates the two arrays using the concat method.
  3. It then sorts the concatenated array using the sort method with a comparator function that compares two elements a and b and returns a negative value if a should come before b, a positive value if a should come after b, 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!