KatInterview

4. Median of Two Sorted Arrays

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the median of two sorted arrays, nums1 and nums2, of sizes m and n. The key constraint is to achieve a time complexity of O(log(m+n)).

Solution

Median of Two Sorted Arrays in Python

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        # Ensure nums1 is the smaller array to optimize binary search range.
        if len(nums1) > len(nums2):
            return self.findMedianSortedArrays(nums2, nums1)

        m, n = len(nums1), len(nums2)
        low, high = 0, m
        # The total number of elements in the left partition.
        half_len = (m + n + 1) // 2

        while low <= high:
            # Partition i for nums1.
            i = (low + high) // 2
            # Corresponding partition j for nums2.
            j = half_len - i

            # Get the four boundary elements.
            max_left1 = nums1[i - 1] if i > 0 else float('-inf')
            min_right1 = nums1[i] if i < m else float('inf')
            max_left2 = nums2[j - 1] if j > 0 else float('-inf')
            min_right2 = nums2[j] if j < n else float('inf')

            # Check if we found the correct partition.
            if max_left1 <= min_right2 and max_left2 <= min_right1:
                # Correct partition found, calculate the median.
                max_left = max(max_left1, max_left2)
                if (m + n) % 2 == 1:
                    # Total length is odd.
                    return max_left
                else:
                    # Total length is even.
                    min_right = min(min_right1, min_right2)
                    return (max_left + min_right) / 2.0
            elif max_left1 > min_right2:
                # Partition i in nums1 is too large, move to the left half.
                high = i - 1
            else:
                # Partition i in nums1 is too small, move to the right half.
                low = i + 1

        # This path should not be reached if inputs are valid.
        return 0.0

Median of Two Sorted Arrays in Java

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        // Ensure nums1 is the smaller array to optimize binary search range.
        if (nums1.length > nums2.length) {
            return findMedianSortedArrays(nums2, nums1);
        }

        int m = nums1.length;
        int n = nums2.length;

        int low = 0, high = m;
        // The total number of elements in the left partition.
        int halfLen = (m + n + 1) / 2;

        while (low <= high) {
            // Partition i for nums1.
            int i = low + (high - low) / 2;
            // Corresponding partition j for nums2.
            int j = halfLen - i;

            // Get the four boundary elements.
            int maxLeft1 = (i == 0) ? Integer.MIN_VALUE : nums1[i - 1];
            int minRight1 = (i == m) ? Integer.MAX_VALUE : nums1[i];
            int maxLeft2 = (j == 0) ? Integer.MIN_VALUE : nums2[j - 1];
            int minRight2 = (j == n) ? Integer.MAX_VALUE : nums2[j];

            // Check if we found the correct partition.
            if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
                // Correct partition found, calculate the median.
                double maxLeft = Math.max(maxLeft1, maxLeft2);
                if ((m + n) % 2 == 1) {
                    // Total length is odd.
                    return maxLeft;
                } else {
                    // Total length is even.
                    double minRight = Math.min(minRight1, minRight2);
                    return (maxLeft + minRight) / 2.0;
                }
            } else if (maxLeft1 > minRight2) {
                // Partition i in nums1 is too large, move to the left half.
                high = i - 1;
            } else {
                // Partition i in nums1 is too small, move to the right half.
                low = i + 1;
            }
        }

        // This line should not be reached if inputs are valid sorted arrays.
        throw new IllegalArgumentException("Input arrays are not sorted or invalid.");
    }
}

Median of Two Sorted Arrays in C++

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        // Ensure nums1 is the smaller array to optimize binary search range.
        if (nums1.size() > nums2.size()) {
            return findMedianSortedArrays(nums2, nums1);
        }

        int m = nums1.size();
        int n = nums2.size();

        int low = 0, high = m;
        // The total number of elements in the left partition.
        int halfLen = (m + n + 1) / 2;

        while (low <= high) {
            // Partition i for nums1.
            int i = low + (high - low) / 2;
            // Corresponding partition j for nums2.
            int j = halfLen - i;

            // Get the four boundary elements.
            int maxLeft1 = (i == 0) ? INT_MIN : nums1[i - 1];
            int minRight1 = (i == m) ? INT_MAX : nums1[i];
            int maxLeft2 = (j == 0) ? INT_MIN : nums2[j - 1];
            int minRight2 = (j == n) ? INT_MAX : nums2[j];

            // Check if we found the correct partition.
            if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
                // Correct partition found, calculate the median.
                double maxLeft = max(maxLeft1, maxLeft2);
                if ((m + n) % 2 == 1) {
                    // Total length is odd.
                    return maxLeft;
                } else {
                    // Total length is even.
                    double minRight = min(minRight1, minRight2);
                    return (maxLeft + minRight) / 2.0;
                }
            } else if (maxLeft1 > minRight2) {
                // Partition i in nums1 is too large, move to the left half.
                high = i - 1;
            } else {
                // Partition i in nums1 is too small, move to the right half.
                low = i + 1;
            }
        }

        // This line should not be reached if inputs are valid sorted arrays.
        return 0.0;
    }
};

Median of Two Sorted Arrays in TypeScript

function findMedianSortedArrays(nums1: number[], nums2: number[]): number {
    // Ensure nums1 is the smaller array to optimize binary search range.
    if (nums1.length > nums2.length) {
        return findMedianSortedArrays(nums2, nums1);
    }

    const m = nums1.length;
    const n = nums2.length;

    let low = 0;
    let high = m;
    // The total number of elements in the left partition.
    const halfLen = Math.floor((m + n + 1) / 2);

    while (low <= high) {
        // Partition i for nums1.
        const i = Math.floor((low + high) / 2);
        // Corresponding partition j for nums2.
        const j = halfLen - i;

        // Get the four boundary elements.
        const maxLeft1 = (i === 0) ? Number.NEGATIVE_INFINITY : nums1[i - 1];
        const minRight1 = (i === m) ? Number.POSITIVE_INFINITY : nums1[i];
        const maxLeft2 = (j === 0) ? Number.NEGATIVE_INFINITY : nums2[j - 1];
        const minRight2 = (j === n) ? Number.POSITIVE_INFINITY : nums2[j];

        // Check if we found the correct partition.
        if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
            // Correct partition found, calculate the median.
            const maxLeft = Math.max(maxLeft1, maxLeft2);
            if ((m + n) % 2 === 1) {
                // Total length is odd.
                return maxLeft;
            } else {
                // Total length is even.
                const minRight = Math.min(minRight1, minRight2);
                return (maxLeft + minRight) / 2.0;
            }
        } else if (maxLeft1 > minRight2) {
            // Partition i in nums1 is too large, move to the left half.
            high = i - 1;
        } else {
            // Partition i in nums1 is too small, move to the right half.
            low = i + 1;
        }
    }

    // This line should not be reached if inputs are valid sorted arrays.
    return 0.0;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.