ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Median of Two Sorted Arrays (Advanced)

Python

Goal -- WPM

Ready
Exercise Algorithm Area
1def findMedianSortedArrays(nums1, nums2):
2"""Finds the median of two sorted arrays in O(log(min(m, n))) time."""
3m, n = len(nums1), len(nums2)
4if m > n:
5nums1, nums2, m, n = nums2, nums1, n, m # Ensure nums1 is the shorter array
6
7imin, imax, half_len = 0, m, (m + n + 1) // 2
8
9while imin <= imax:
10i = (imin + imax) // 2
11j = half_len - i
12
13if i < m and nums2[j-1] > nums1[i]:
14# i is too small, must increase it
15imin = i + 1
16elif i > 0 and nums1[i-1] > nums2[j]:
17# i is too big, must decrease it
18imax = i - 1
19else:
20# i is perfect
21if i == 0: max_of_left = nums2[j-1]
22elif j == 0: max_of_left = nums1[i-1]
23else: max_of_left = max(nums1[i-1], nums2[j-1])
24
25if (m + n) % 2 == 1:
26return max_of_left
27
28if i == m: min_of_right = nums2[j]
29elif j == n: min_of_right = nums1[i]
30else: min_of_right = min(nums1[i], nums2[j])
31
32return (max_of_left + min_of_right) / 2.0
33return 0.0 # Should not reach here if inputs are valid
Algorithm description viewbox

Median of Two Sorted Arrays (Advanced)

Algorithm description:

This function finds the median of two sorted arrays efficiently. It's a common interview problem that tests understanding of binary search and partitioning. A real-world application could be in data analysis where you need to find the median of combined datasets without merging them entirely.

Algorithm explanation:

The algorithm uses binary search on the shorter array to find the correct partition point. The goal is to divide both arrays into two parts such that all elements in the left parts are less than or equal to all elements in the right parts, and the total number of elements in the left parts is equal to `half_len`. The time complexity is O(log(min(m, n))) because we perform binary search on the shorter array. Space complexity is O(1) as we only use a few variables. Edge cases include empty arrays, arrays of different lengths, and handling the median calculation for odd/even total number of elements.

Pseudocode:

function findMedianSortedArrays(nums1, nums2):
  ensure nums1 is the shorter array
  m = length of nums1, n = length of nums2
  half_len = (m + n + 1) / 2
  imin = 0, imax = m

  while imin <= imax:
    i = (imin + imax) / 2
    j = half_len - i

    if nums2[j-1] > nums1[i]:
      imin = i + 1
    elif nums1[i-1] > nums2[j]:
      imax = i - 1
    else:
      # Found correct partition
      max_of_left = max(nums1[i-1] if i>0 else -infinity, nums2[j-1] if j>0 else -infinity)
      if (m+n) is odd:
        return max_of_left
      min_of_right = min(nums1[i] if i<m else +infinity, nums2[j] if j<n else +infinity)
      return (max_of_left + min_of_right) / 2.0
  return error