Median of Two Sorted Arrays of Different Sizes using JavaScript

Given two arrays, our goal is to find the median of two sorted arrays of different sizes by merging both of them. The median is the middle value of the array after dividing it into two halves.

Example:

Input:  Arr1: [1,4,5], Arr2: [2,8,7,3]
Output: Median = 4
Explanation: The merged and sorted array is: ar3[] = [1,2,3,4,5,7,8]
The median is 4

Table of Content

  • Using Binary Search
  • Using Two-Pointers Approach

Using Binary Search

In this approach, we will be performing binary search on the shorter array so that we can partition it in such a way that the newly combined left half of both the arrays will have elements less than the combined right half. Adjust the partition point until the condition for median gets satisfied. If the combined length of the new array is odd, return the maximum element of the left partition. If it’s even, return the average of the maximum element of the left partition and the minimum element of the right partition.

Example: The below example shows how to find Median of two sorted arrays of different sizes using Binary Search on the Smaller Array.

JavaScript
function find_Median_Fun(no1, no2) {
    
    //    Checks whether no1 is the smaller array 
    if (no1.length > no2.length) {
        return find_Median_Fun(no2, no1);
    }
    const m = no1.length; 
    const n = no2.length; 
    let low = 0, high = m; 

    // Perform binary search
    while (low <= high) {
        // Calculate partition points
        const partitionX = Math.floor((low + high) / 2); 
        const partitionY = Math.floor((m + n + 1) / 2) - partitionX; 

        // Find elements to the left and 
        // right of the partition for both arrays
        const maxX = partitionX === 0 ? 
                     Number.NEGATIVE_INFINITY : 
                     no1[partitionX - 1];
        const maxY = partitionY === 0 ?
                     Number.NEGATIVE_INFINITY : 
                     no2[partitionY - 1];
        const minX = partitionX === m ? 
                     Number.POSITIVE_INFINITY : 
                     no1[partitionX];
        const minY = partitionY === n ? 
                     Number.POSITIVE_INFINITY : 
                     no2[partitionY];

        // Check if partitions are correct
        if (maxX <= minY && maxY <= minX) {
            
            // If the combined length of the arrays is even
            // return the average of the middle elements
            if ((m + n) % 2 === 0) {
                return (Math.max(maxX, maxY) +
                        Math.min(minX, minY)) / 2;
            } else {
                
                // If the combined length of the arrays is odd,
                // return the maximum of the middle elements
                return Math.max(maxX, maxY);
            }
        } else if (maxX > minY) {
            
            // If partitionX is too big,
            // move partitionX to the left
            high = partitionX - 1;
        } else {
            
            // If partitionX is too small,
            // move partitionX to the right
            low = partitionX + 1;

        }
    }
}

const no1 = [1, 3];
const no2 = [2];
console.log(find_Median_Fun(no1, no2));

Output
2

Time Complexity: O(log(min(m, n))), where m and n are the lengths of the two input arrays.

Space Complexity: O(1)

Using Two-Pointers Approach

The function find_Median_fun finds the median of two sorted arrays by iterating through them simultaneously with two pointers, selecting elements in ascending order until reaching the middle point of the combined arrays. It determines the median based on whether the total length is even or odd and returns the result accordingly.

Example: The example below shows how to find Median of two sorted arrays of different sizes using JavaScript Using Two-Pointers.

JavaScript
function find_Median_fun(nums1, nums2) {
    const totalLength = nums1.length + nums2.length;
    const ifEven = totalLength % 2 === 0;
    const halfLength = Math.floor(totalLength / 2);

    // 2 pointers
    let i = 0, j = 0;
    let count = 0;
    let median = 0, prevMedian = 0;

    while (count <= halfLength) {
        prevMedian = median;
        if (i < nums1.length && 
            (j >= nums2.length || nums1[i] < nums2[j])) {
            median = nums1[i];
            i++;
        } else {
            median = nums2[j];
            j++;
        }
        count++;
    }

    // If length is even 
    if (ifEven) {
        return (prevMedian + median) / 2;
    } else {
        return median;
    }
}

const nums1 = [1, 3];
const nums2 = [2];
console.log("Median:", 
             find_Median_fun(nums1, nums2));

Output
Median: 2

Time Complexity: O(m + n), where m and n are the lengths of the two input arrays.

Space Complexity: O(1)



Contact Us