
Sponsored
Sponsored
This approach leverages binary search to reduce the problem to a smaller size, achieving the desired O(log(m + n)) complexity. The strategy involves performing binary search on the smaller array to find the perfect partition point.
Time complexity: O(log(min(m,n))). Space complexity: O(1).
1def findMedianSortedArrays(nums1, nums2):
2 if len(nums1) > len(nums2):
3 nums1, nums2 = nums2, nums1
4 x, y = len(nums1), len(nums2)
5 low, high = 0, x
6 while low <= high:
7 partitionX = (low + high) // 2
8 partitionY = (x + y + 1) // 2 - partitionX
9 maxX = float('-inf') if partitionX == 0 else nums1[partitionX - 1]
10 minX = float('inf') if partitionX == x else nums1[partitionX]
11 maxY = float('-inf') if partitionY == 0 else nums2[partitionY - 1]
12 minY = float('inf') if partitionY == y else nums2[partitionY]
13 if maxX <= minY and maxY <= minX:
14 if (x + y) % 2 == 0:
15 return (max(maxX, maxY) + min(minX, minY)) / 2
16 else:
17 return max(maxX, maxY)
18 elif maxX > minY:
19 high = partitionX - 1
20 else:
21 low = partitionX + 1
22 raise ValueError("The input arrays are not sorted.")The Python solution iteratively adjusts partitioning using binary search principles, comparing maximum and minimum values at each step to converge on the correct median values. Python's float('-inf') and float('inf') handle boundary cases like in other languages.
This approach focuses on merging the two sorted arrays as naturally done in merge sort, and then finding the median directly from the merged result. Though this solution has a higher time complexity, it's easier to implement and understand.
Time complexity: O(m + n). Space complexity: O(m + n).
1#
The C implementation uses an auxiliary array to merge the two sorted arrays into one. After merging, we calculate the median of the merged array based on its even or odd length. Memory allocation and deallocation are crucial to manage space efficiently.