Merge Two Sorted Arrays


Instructions

Write a function that merges two sorted arrays into a single sorted array.


Examples

Here are a few examples to illustrate how the mergeSortedArrays function works:

Example 1

Input: arr1 = [1, 4, 5], arr2 = [2, 3, 6, 7, 8] Output: [1, 2, 3, 4, 5, 6, 7, 8]

Example 2

Input: arr1 = [1, 3, 5], arr2 = [2, 4, 6] Output: [1, 2, 3, 4, 5, 6]

Example 3

Input: arr1 = [0, 2, 4], arr2 = [1, 3, 5] Output: [0, 1, 2, 3, 4, 5]


Solution

The example solution provided demonstrates a function called mergeSortedArrays that merges two sorted arrays into a single sorted array. The function uses a two-pointer technique to iterate through both arrays and merge them in sorted order.

Merge Sorted Arrays

  const mergeSortedArrays = (arr1, arr2) => {
    let mergedArray = [];
    let i = 0, j = 0;

    while (i < arr1.length && j < arr2.length) {
      if (arr1[i] < arr2[j]) {
        mergedArray.push(arr1[i]);
        i++;
      } else {
        mergedArray.push(arr2[j]);
        j++;
      }
    }

    // Add remaining elements of arr1 and arr2 using spread operator
    if (i < arr1.length) {
      return [...mergedArray, ...arr1.slice(i)]
    }
    if (j < arr2.length) {
      return [...mergedArray, ...arr2.slice(j)]
    }

    return mergedArray;
  }

Was this page helpful?