DEV Community

Chandrasekar Gokulanathan
Chandrasekar Gokulanathan

Posted on

4. Median of Two Sorted Arrays

Problem #4: https://leetcode.com/problems/median-of-two-sorted-arrays/

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

Example 1:

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Enter fullscreen mode Exit fullscreen mode

Example 3:

Input: nums1 = [0,0], nums2 = [0,0]
Output: 0.00000
Enter fullscreen mode Exit fullscreen mode

Example 4:

Input: nums1 = [], nums2 = [1]
Output: 1.00000
Enter fullscreen mode Exit fullscreen mode

Example 5:

Input: nums1 = [2], nums2 = []
Output: 2.00000
Enter fullscreen mode Exit fullscreen mode

Solution

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
var findMedianSortedArrays = function(nums1, nums2) {
    let sortedArray = [...nums1, ...nums2].sort((a,b) => a-b);
    let median = 0;

    if (sortedArray.length % 2 !== 0) {
        median = sortedArray[Math.floor(sortedArray.length / 2)];    
    } else {
        median = (sortedArray[(sortedArray.length/2)] + sortedArray[(sortedArray.length/2) -1])/2;
    }

    return median;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)