Mnewsfr.com

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.

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.

Your Task :

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

To find the median of two sorted arrays nums1 and nums2, you can follow a binary search approach that combines both arrays to find the partition points that divide the combined arrays into two halves of approximately equal length. Here’s a step-by-step guide on how to do it

  1. Ensure nums1 is the smaller array (if not, swap them) to optimize the partitioning process.
  2. Use binary search on the smaller array (nums1) to find a partition index partition1 such that the elements to the left of partition1 are smaller than or equal to the elements on the right.
  3. Calculate the corresponding partition index partition2 in the larger array (nums2) using the formula partition2 = (m + n + 1) / 2 - partition1.
  4. Calculate the four boundary values: maxLeft1, maxLeft2, minRight1, and minRight2. These represent the elements around the partition points.
    • maxLeft1 = nums1[partition1 - 1] if partition1 > 0, otherwise negative infinity
    • maxLeft2 = nums2[partition2 - 1] if partition2 > 0, otherwise negative infinity
    • minRight1 = nums1[partition1] if partition1 < m, otherwise positive infinity
    • minRight2 = nums2[partition2] if partition2 < n, otherwise positive infinity
  5. Check if the combined length of the two arrays (m + n) is even or odd. If even, the median is (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) / 2. If odd, the median is max(maxLeft1, maxLeft2).

Median of Two Sorted Arrays using Python

def findMedianSortedArrays(nums1, nums2):
    if len(nums1) > len(nums2):
        nums1, nums2 = nums2, nums1

    m, n = len(nums1), len(nums2)
    low, high = 0, m

    while low <= high:
        partition1 = (low + high) // 2
        partition2 = (m + n + 1) // 2 - partition1

        maxLeft1 = float('-inf') if partition1 == 0 else nums1[partition1 - 1]
        maxLeft2 = float('-inf') if partition2 == 0 else nums2[partition2 - 1]
        minRight1 = float('inf') if partition1 == m else nums1[partition1]
        minRight2 = float('inf') if partition2 == n else nums2[partition2]

        if maxLeft1 <= minRight2 and maxLeft2 <= minRight1:
            if (m + n) % 2 == 0:
                return (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) / 2
            else:
                return max(maxLeft1, maxLeft2)
        elif maxLeft1 > minRight2:
            high = partition1 - 1
        else:
            low = partition1 + 1

    raise ValueError("Input arrays are not sorted!")

Median of Two Sorted Arrays using C#

public double FindMedianSortedArrays(int[] nums1, int[] nums2) {
    if (nums1.Length > nums2.Length) {
        int[] temp = nums1;
        nums1 = nums2;
        nums2 = temp;
    }

    int m = nums1.Length;
    int n = nums2.Length;
    int low = 0;
    int high = m;

    while (low <= high) {
        int partition1 = (low + high) / 2;
        int partition2 = (m + n + 1) / 2 - partition1;

        int maxLeft1 = (partition1 == 0) ? int.MinValue : nums1[partition1 - 1];
        int maxLeft2 = (partition2 == 0) ? int.MinValue : nums2[partition2 - 1];
        int minRight1 = (partition1 == m) ? int.MaxValue : nums1[partition1];
        int minRight2 = (partition2 == n) ? int.MaxValue : nums2[partition2];

        if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
            if ((m + n) % 2 == 0) {
                return (Math.Max(maxLeft1, maxLeft2) + Math.Min(minRight1, minRight2)) / 2.0;
            } else {
                return Math.Max(maxLeft1, maxLeft2);
            }
        } else if (maxLeft1 > minRight2) {
            high = partition1 - 1;
        } else {
            low = partition1 + 1;
        }
    }

    throw new ArgumentException("Input arrays are not sorted!");
}

Median of Two Sorted Arrays using Java

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    if (nums1.length > nums2.length) {
        int[] temp = nums1;
        nums1 = nums2;
        nums2 = temp;
    }

    int m = nums1.length;
    int n = nums2.length;
    int low = 0;
    int high = m;

    while (low <= high) {
        int partition1 = (low + high) / 2;
        int partition2 = (m + n + 1) / 2 - partition1;

        int maxLeft1 = (partition1 == 0) ? Integer.MIN_VALUE : nums1[partition1 - 1];
        int maxLeft2 = (partition2 == 0) ? Integer.MIN_VALUE : nums2[partition2 - 1];
        int minRight1 = (partition1 == m) ? Integer.MAX_VALUE : nums1[partition1];
        int minRight2 = (partition2 == n) ? Integer.MAX_VALUE : nums2[partition2];

        if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
            if ((m + n) % 2 == 0) {
                return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2.0;
            } else {
                return Math.max(maxLeft1, maxLeft2);
            }
        } else if (maxLeft1 > minRight2) {
            high = partition1 - 1;
        } else {
            low = partition1 + 1;
        }
    }

    throw new IllegalArgumentException("Input arrays are not sorted!");
}

Median of Two Sorted Arrays using Java Script

var findMedianSortedArrays = function(nums1, nums2) {
    if (nums1.length > nums2.length) {
        [nums1, nums2] = [nums2, nums1]; // Swap arrays if needed
    }

    const m = nums1.length;
    const n = nums2.length;
    let low = 0;
    let high = m;

    while (low <= high) {
        const partition1 = Math.floor((low + high) / 2);
        const partition2 = Math.floor((m + n + 1) / 2) - partition1;

        const maxLeft1 = (partition1 === 0) ? -Infinity : nums1[partition1 - 1];
        const maxLeft2 = (partition2 === 0) ? -Infinity : nums2[partition2 - 1];
        const minRight1 = (partition1 === m) ? Infinity : nums1[partition1];
        const minRight2 = (partition2 === n) ? Infinity : nums2[partition2];

        if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
            if ((m + n) % 2 === 0) {
                return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2;
            } else {
                return Math.max(maxLeft1, maxLeft2);
            }
        } else if (maxLeft1 > minRight2) {
            high = partition1 - 1;
        } else {
            low = partition1 + 1;
        }
    }

    throw new Error("Input arrays are not sorted!");
};

The overall run time complexity should be O(log (m+n)).

Constraints

nums1.length == m | nums2.length == n | 0 <= m <= 1000 | 0 <= n <= 1000 | 1 <= m + n <= 2000 | -106 <= nums1[i], nums2[i] <= 106