#4
Median of Two Sorted Arrays
hard· Binary Searchruns: 0Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity must be O(log(min(m, n))).
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 957
class Solution:
def findMedianSortedArrays(
self, nums1: list[int], nums2: list[int]
) -> float:
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
m, n = len(nums1), len(nums2)
total = m + n
half = (total + 1) // 2
left, right = 0, m
while left <= right:
i = (left + right) // 2
j = half - i
left1 = nums1[i - 1] if i > 0 else float("-inf")
right1 = nums1[i] if i < m else float("inf")
left2 = nums2[j - 1] if j > 0 else float("-inf")
right2 = nums2[j] if j < n else float("inf")
if left1 <= right2 and left2 <= right1:
if total % 2:
return max(left1, left2)
return (max(left1, left2) + min(right1, right2)) / 2
if left1 > right2:
right = i - 1
else:
left = i + 1
return 0.0
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.