Skip to content

Example: Median Of Two Sorted Arrays

Roberto Fronteddu edited this page Mar 17, 2024 · 1 revision
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) { 
        // first array must be smaller than second for alg
        return nums1.length <= nums2.length ? median(nums1, nums2) : median(nums2, nums1);
    }


    double median(int[] nums1, int[] nums2) {
        // To find the median of two sorted arrays nums1 and nums2, 
        // we can use the concept of binary search. 
        
        // The idea is to partition both arrays such that the elements 
        // on the left side are smaller than or equal to the elements on the right side. 
        // Then, the median can be found based on these partitions.

  
        // 1. binary search to find partition point such that
        //      number of elements on the left of num1 partition l1 +
        //      number of elements on the left of num2 partition l2 ==
        //      half of the total number of elements             (n + m + 1) / 2
        //      l1 + l2 = (n + m + 1) / 2
        // 2. calculate median based on the partition

        int m = nums1.length;
        int n = nums2.length;
        int left = 0;
        int right = m;
   
        while (left <= right) {
            int partition1 = left + (right - left) / 2;
            
            // Adding 1 ensures partition2 is at least 1, guaranteeing some elements on the left side of nums2.
            int partition2 = (m + n + 1) / 2 - partition1;

            // find max element on the left of each partition.
            // find min element on the right of each partition.
            // Finding elements around partitions
            int maxLeft1 = (partition1 == 0) ? Integer.MIN_VALUE : nums1[partition1 - 1];
            int minRight1 = (partition1 == m) ? Integer.MAX_VALUE : nums1[partition1];

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

            // All elements on the left side of partition1 in nums1 must be less than or equal to 
            // all elements on the right side of partition2 in nums2
            
            // all elements on the left side of partition2 in nums2 must be less than or equal to 
            // all elements on the right side of partition1 in nums1. 
            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) {
                right = partition1 - 1;
            } else {
                left = partition1 + 1;
            }
        }
        return -1;
    }
}
Clone this wiki locally