Skip to content

Commit e3cea9b

Browse files
Add median of two sorted arrays implementation #13717 [Hacktoberfest]
1 parent e2a78d4 commit e3cea9b

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
"""
2+
Median of Two Sorted Arrays
3+
4+
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
5+
6+
The overall run time complexity should be O(log(m + n)).
7+
8+
Examples:
9+
Example 1:
10+
Input: nums1 = [1, 3], nums2 = [2]
11+
Output: 2.00000
12+
Explanation: merged array = [1, 2, 3] and median is 2.
13+
14+
Example 2:
15+
Input: nums1 = [1, 2], nums2 = [3, 4]
16+
Output: 2.50000
17+
Explanation: merged array = [1, 2, 3, 4] and median is (2 + 3) / 2 = 2.5.
18+
19+
Constraints:
20+
* nums1.length == m
21+
* nums2.length == n
22+
* 0 <= m <= 1000
23+
* 0 <= n <= 1000
24+
* 1 <= m + n <= 2000
25+
* -10^6 <= nums1[i], nums2[i] <= 10^6
26+
27+
Implementation: Divide and Conquer (Binary Search on partitions).
28+
Time Complexity: O(log(min(m, n)))
29+
Space Complexity: O(1)
30+
"""
31+
32+
from typing import List
33+
34+
35+
def find_median_sorted_arrays(nums1: List[int], nums2: List[int]) -> float:
36+
"""
37+
Find the median of two sorted arrays using binary search on partitions.
38+
39+
Args:
40+
nums1 (List[int]): First sorted array
41+
nums2 (List[int]): Second sorted array
42+
43+
Returns:
44+
float: Median of the two arrays
45+
"""
46+
# Ensure nums1 is the smaller array
47+
if len(nums1) > len(nums2):
48+
nums1, nums2 = nums2, nums1
49+
50+
m, n = len(nums1), len(nums2)
51+
left, right = 0, m
52+
53+
# Binary search for the partition in nums1
54+
while left <= right:
55+
i = (left + right) // 2 # Partition in nums1
56+
j = (m + n + 1) // 2 - i # Partition in nums2
57+
58+
# Edge cases for partitions
59+
left1 = float('-inf') if i == 0 else nums1[i - 1]
60+
right1 = float('inf') if i == m else nums1[i]
61+
left2 = float('-inf') if j == 0 else nums2[j - 1]
62+
right2 = float('inf') if j == n else nums2[j]
63+
64+
# Check if this partition is correct
65+
if left1 <= right2 and left2 <= right1:
66+
# Correct partition found
67+
if (m + n) % 2 == 0:
68+
# Even length: average of max(lefts) and min(rights)
69+
return (max(left1, left2) + min(right1, right2)) / 2
70+
else:
71+
# Odd length: max of lefts
72+
return max(left1, left2)
73+
elif left1 > right2:
74+
# Move partition left in nums1
75+
right = i - 1
76+
else:
77+
# Move partition right in nums1
78+
left = i + 1
79+
80+
# Should not reach here if inputs are valid
81+
raise ValueError("Input arrays are not sorted or invalid")
82+
83+
84+
# Optional: Add simple tests
85+
if __name__ == "__main__":
86+
assert abs(find_median_sorted_arrays([1, 3], [2]) - 2.0) < 1e-5
87+
assert abs(find_median_sorted_arrays([1, 2], [3, 4]) - 2.5) < 1e-5
88+
print("All tests passed!")

0 commit comments

Comments
 (0)