average of two sorted arrays in typescript

You can find the average of two sorted arrays by first merging the sorted arrays into a single sorted array, and then finding the median of the merged array. Here's how to do it in TypeScript:

index.ts
function averageOfTwoSortedArrays(arr1: number[], arr2: number[]): number {
  const mergedArray: number[] = [];
  let i = 0;
  let j = 0;

  // Merge the two sorted arrays into one sorted array
  while (i < arr1.length && j < arr2.length) {
    if (arr1[i] < arr2[j]) {
      mergedArray.push(arr1[i++]);
    } else {
      mergedArray.push(arr2[j++]);
    }
  }
  while (i < arr1.length) {
    mergedArray.push(arr1[i++]);
  }
  while (j < arr2.length) {
    mergedArray.push(arr2[j++]);
  }

  // Find the median of the merged array
  const mid = Math.floor(mergedArray.length / 2);
  if (mergedArray.length % 2 === 0) {
    return (mergedArray[mid - 1] + mergedArray[mid]) / 2;
  } else {
    return mergedArray[mid];
  }
}
727 chars
29 lines

In this implementation, we use two pointers to iterate over the two arrays and insert the smaller of the two at each step. After the arrays are merged, we find the median of the merged array by checking if its length is even or odd.

Note that the input arrays must be sorted in ascending order for this implementation to work correctly.

gistlibby LogSnag