4 Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5
// O(n) O(n) space attempt - working
def findMedianSortedArrays(nums1, nums2):
    """
    :type nums1: List[int]
    :type nums2: List[int]
    :rtype: float
    """

    new_size = len(nums1) + len(nums2)
    if (new_size == 0):
        return -1

    iter_nums1 = 0
    iter_nums2 = 0
    new_list = [0] * new_size
    for i in range(0, new_size):
        if (iter_nums1 >= len(nums1)):
            new_list[i] = nums2[iter_nums2]
            iter_nums2 += 1
        elif (iter_nums2 >= len(nums2)):
            new_list[i] = nums1[iter_nums1]
            iter_nums1 += 1
        elif (nums1[iter_nums1] > nums2[iter_nums2]):
            new_list[i] = nums2[iter_nums2]
            iter_nums2 += 1
        else:
            new_list[i] = nums1[iter_nums1]
            iter_nums1 += 1

    med_index = int(new_size / 2)
    if (new_size % 2 == 0):
        return (new_list[med_index] + new_list[med_index - 1]) / 2
    else:
        return new_list[med_index]

print(findMedianSortedArrays([1, 3], [2]))
print(findMedianSortedArrays([1,2],[3,4]))

Last updated