codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Practice] Merge two sorted arrays #28

Open lpatmo opened 5 years ago

lpatmo commented 5 years ago
Given two sorted arrays, merge them together. 
Test cases:
merge([1, 3, 5,11],[2,4,6]) => [1,2,3,4,5,6,11]
merge([], [2,9,11]); => [2,9,11]
merge([1, 2, 3], []); => [1,2,3]
merge([]. []) => []
lpatmo commented 5 years ago

function mergeSorted(arr1,arr2) {
  let results = [];
  let i = 0, j = 0;
  while(i < arr1.length && j < arr2.length) {
    if (arr2[j] > arr1[i]) {
      results.push(arr1[i])
      i++;
    } else {
      results.push(arr2[j]);
      j++;
    }
  }
 //once we've exceeded the index on one of them (i.e. one array is longer than the other one)
  while (i < arr1.length) {
    results.push(arr1[i])
    i++;
  }
  while (j < arr1.length) {
    results.push(arr2[j])
    j++;
  }
  return results;
}
lpatmo commented 5 years ago

Recursive solution:


function mergeSorted(arr1, arr2){
  //base case: arr1 and arr2 are empty, return empty arr
  //if arr1 empty, return arr2
  // if arr2 empty, return arr1
  // otherwise, compare arr1[0] and arr2[0] and return the smallest number + merge(arr1.slice(1), arr2)
  if (arr1.length === 0 && arr2.length === 0) {
    return [];
  } else if (arr1.length === 0 && arr2.length > 0) {
    return arr2;
  } else if (arr2.length === 0 && arr1.length > 0) {
    return arr1;
  } else if (arr1[0] < arr2[0]) {
    return [arr1[0]].concat(merge(arr1.slice(1), arr2))
  } else if (arr1[0] > arr2[0]) {
    return [arr2[0]].concat(merge(arr1, arr2.slice(1)))
  }
}
ArcTanSusan commented 5 years ago

What about the unittests? Adding in unittests is a common requirement in coding exams.

gauravchl commented 5 years ago

One liner es flavored lazy solution

const merge = (arr1=[], arr2=[]) => ([...arr1, ...arr2].sort((a, b)=> a - b))