DEV Community

Seth
Seth

Posted on • Edited on

Median of Two Sorted Arrays

This question is deemed "Hard", but it's not too bad at all.

Let's assume we've got two parameters in our function, each are an array of nums.


function medianTwoArrays(num1, nums2) {

}
Enter fullscreen mode Exit fullscreen mode

The first thing we can do is concat them together, and then sort the newly created array from lowest to highest.

function medianTwoArrays(num1, nums2) {
  let newArray = nums1.concat(nums2)
  let sorted = newArray.sort((a,b) => a - b)
}

Enter fullscreen mode Exit fullscreen mode

Cool. We've now got a sorted merged array. Now to determine whether we have an odd or even amount of elements in our array.

If the length of the new array is even, we will take the two numbers separating the lower and upper half of the array, add them together, and divide them by two.

Doing so is simple. If the length modulo 2 is 0, then its even. If it has a remainder of 1, then it's odd. When its odd, we want to divide the length by 2 and the remove .5 from the index.

For example, if we have 5 elements, and we want the third, we can do 5 divided by 2 which is 2.5 and minus .5 we have 2 (which is the index, so we're talking about the third element).

function medianTwoArrays(num1, nums2) {
  let newArray = nums1.concat(nums2)
  let sorted = newArray.sort((a,b) => a - b)

  if (sorted.length % 2 === 1) {
    return sorted[(sorted.length/2) -.5]
  } 
    else {

  }
}
Enter fullscreen mode Exit fullscreen mode

Now lets focus on the other part of the problem, if we have 8 numbers, or 4 numbers, in the array.

To solve this we will want to get the number in the lower boundary, and the number in the upper boundary, then we will divide both by 2.

function medianTwoArrays(num1, nums2) {
  let newArray = nums1.concat(nums2)
  let sorted = newArray.sort((a,b) => a - b)

  if (sorted.length % 2 === 1) {
    return sorted[(sorted.length/2) -.5]
  } 
    else {
 return (sorted[sorted.length/2] + sorted[sorted.length/2 -1]) /2
  }
}
Enter fullscreen mode Exit fullscreen mode

And voila. We've managed to return the median whether the length of the merged and sorted array is odd or even.

Top comments (1)

Collapse
 
rohithv07 profile image
Rohith V

Great also just an FYI There is a binary search approach for the same problem.