LeetSolved

Find solutions to all LeetCode problems here.

4.

Median of Two Sorted Arrays

Hard

Problem Description

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

Examples

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: The median is 2.

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: The median is (2 + 3) / 2 = 2.5.

Constraints

Approach to Solve

Use a two-pointer technique to merge the two arrays and find the median.

Code Implementation

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        m, n = len(nums1), len(nums2)
        if m > n:
            nums1, nums2, m, n = nums2, nums1, n, m
        imin, imax, half_len = 0, m, (m + n + 1) // 2
        while imin <= imax:
            i = (imin + imax) // 2
            j = half_len - i
            if i < m and nums2[j-1] > nums1[i]:
                imin = i + 1
            elif i > 0 and nums1[i-1] > nums2[j]:
                imax = i - 1
            else:
                if i == 0:
                    max_left = nums2[j-1]
                elif j == 0:
                    max_left = nums1[i-1]
                else:
                    max_left = max(nums1[i-1], nums2[j-1])
                if (m + n) % 2 == 1:
                    return max_left
                if i == m:
                    min_right = nums2[j]
                elif j == n:
                    min_right = nums1[i]
                else:
                    min_right = min(nums1[i], nums2[j])
                return (max_left + min_right) / 2.0
        return 0.0

Explanation

We use a binary search approach to find the median. We partition the two arrays such that the left half contains the smaller elements and the right half contains the larger elements. We then adjust the partition until the median is found.

Complexity

  • Time Complexity: O(log(min(m, n)))
  • Space Complexity: O(1)
Code copied to clipboard!