Algorithm Day69 - Median of Two Sorted Arrays

🧩 Problem Description

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

The overall runtime complexity should be O(log (m+n)).


💬 Examples

Example 1

1
2
Input: nums1 = [1,3], nums2 = [2]
Output: 2.0

Example 2

1
2
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.5

Example 3

1
2
Input: nums1 = [0,0], nums2 = [0,0]
Output: 0.0

💡 Intuition

We need to find the k-th smallest element in two sorted arrays efficiently.

  • Partition both arrays so that the left half and right half are balanced.
  • Ensure all elements in the left half are ≤ all elements in the right half.
  • Depending on the total length being odd/even, return middle or average of two middle values.

This can be solved with binary search on the partition.


🔢 Java Code (Binary Search Partition)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1.length > nums2.length) {
return findMedianSortedArrays(nums2, nums1);
}

int m = nums1.length, n = nums2.length;
int left = 0, right = m;

while (left <= right) {
int i = (left + right) / 2;
int j = (m + n + 1) / 2 - i;

int left1 = (i == 0) ? Integer.MIN_VALUE : nums1[i - 1];
int right1 = (i == m) ? Integer.MAX_VALUE : nums1[i];
int left2 = (j == 0) ? Integer.MIN_VALUE : nums2[j - 1];
int right2 = (j == n) ? Integer.MAX_VALUE : nums2[j];

if (left1 <= right2 && left2 <= right1) {
if ((m + n) % 2 == 0) {
return (Math.max(left1, left2) + Math.min(right1, right2)) / 2.0;
} else {
return Math.max(left1, left2);
}
} else if (left1 > right2) {
right = i - 1;
} else {
left = i + 1;
}
}
throw new IllegalArgumentException();
}
}

⏱ Complexity Analysis

  • Time: O(log(min(m, n))) — binary search only on smaller array.
  • Space: O(1).

✍️ Summary

  • Partition both arrays using binary search.
  • Compare partition edges to decide where to move.
  • Handle odd/even total length cases.

Related problems

  • lc-33 — Search in Rotated Sorted Array
  • lc-153 — Find Minimum in Rotated Sorted Array