LeetCode: Median of Two Sorted Arrays — JavaScript

Vakas Akhtar
3 min readDec 22, 2020

In this article I’ll be going over a JavaScript solution to a leetcode hard question that’s asking us to find the median of two sorted arrays. The problem is as follows:

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

So for example if we were given the following inputs we should get an output that displays the median.

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000

To get to our solution the first thing I’d do is merge the two arrays. Once the arrays have been merged we can sort them. Once we have the merged array sorted we’ll be able to calculate the median.

var findMedianSortedArrays = function(nums1, nums2) {
const nums = nums1.concat(nums2)
//join the two arrays together using concat

nums.sort( function(a,b) { return a - b; } )
//sort the newly created array
};

Now we can go ahead and find our median. When there’s an odd number of numbers in the sample you can simply add 1 to the total number of numbers in the sample and divide by 1 to get the median. For example if there are 5 numbers in a sample you can add 1 and divide that number by 2 to get the median 3. If there is an even amount of numbers in the sample you’d have to divide the total number of the sample by 2 and add 1. You’ll then have the two numbers in the middle of the sample that you would calculate the average of in order to find the median. So if you had a sample with 10 numbers you would have to divide by 2 which results in 5. Then add 1 to five to get the second number that is in the middle of the sample. Now you can take the average of the numbers at the 5th and 6th positions of the sample.

var findMedianSortedArrays = function(nums1, nums2) {
const nums = nums1.concat(nums2)
nums.sort( function(a,b) { return a - b; } )
if (((nums.length + 1) % 2 ) === 0){
let median = (nums.length + 1)/2
//find the index of the median in the array
return nums[median - 1]
//you need to subtract one from the index since arrays start at 0

} else {
let first = (nums.length/2)
//index of the first median
let second = first + 1
//index of the second median
let med1 = nums[first - 1]
let med2 = nums[second - 1]
const median = (med1 + med2)/2
//calculate the average of the two medians
return median
}
};

Nice! Looks like our algorithm works. Now that you have an understanding of how to solve the problem I’m sure you can find a solution that’s more efficient than mine. In fact, I’ll most likely try to rework my solution and find something more efficient in the future. Thanks for reading and good luck to everyone on their leetcode grind!

--

--