⬅ Previous Topic
Minimize Maximum Distance Between Gas StationsNext Topic ⮕
K-th Element of Two Sorted Arrays⬅ Previous Topic
Minimize Maximum Distance Between Gas StationsNext Topic ⮕
K-th Element of Two Sorted ArraysTopic Contents
You are given two sorted arrays that can be of different sizes. Your task is to find the median of the combined sorted array formed by merging the two arrays.
Try to solve the problem in an efficient way using binary search, with a time complexity of O(log(min(n, m))
, where n
and m
are the lengths of the two arrays.
nums1
and nums2
. Always apply binary search on the smaller array to minimize time.low = 0
and high = length of nums1
.low ≤ high
, do the following:partitionX = (low + high) / 2
.partitionY = (n + m + 1)/2 - partitionX
.maxLeftX
, minRightX
, maxLeftY
, and minRightY
using partition indices.maxLeftX ≤ minRightY
and maxLeftY ≤ minRightX
, you found the correct partition.low
or high
accordingly.def findMedianSortedArrays(nums1, nums2):
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
x, y = len(nums1), len(nums2)
low, high = 0, x
while low <= high:
partitionX = (low + high) // 2
partitionY = (x + y + 1) // 2 - partitionX
maxLeftX = float('-inf') if partitionX == 0 else nums1[partitionX - 1]
minRightX = float('inf') if partitionX == x else nums1[partitionX]
maxLeftY = float('-inf') if partitionY == 0 else nums2[partitionY - 1]
minRightY = float('inf') if partitionY == y else nums2[partitionY]
if maxLeftX <= minRightY and maxLeftY <= minRightX:
if (x + y) % 2 == 0:
return (max(maxLeftX, maxLeftY) + min(minRightX, minRightY)) / 2.0
else:
return max(maxLeftX, maxLeftY)
elif maxLeftX > minRightY:
high = partitionX - 1
else:
low = partitionX + 1
return 0.0
print(findMedianSortedArrays([1, 3], [2]))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | Median found on the first partition guess if the arrays are perfectly balanced. |
Average Case | O(log(min(n, m))) | Binary search on the smaller array ensures logarithmic steps for finding the correct partition. |
Average Case | O(log(min(n, m))) | In worst case, binary search continues until all elements in the smaller array are checked. |
O(1)
Explanation: Only a fixed number of variables are used for partitioning logic. No extra space is required.
⬅ Previous Topic
Minimize Maximum Distance Between Gas StationsNext Topic ⮕
K-th Element of Two Sorted ArraysYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.