#4
Median of Two Sorted Arrays
HardArrayBinary SearchDivide and ConquerBinary SearchArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Binary Search)★ | |
|---|---|---|
| Time | O(n log n) | O(log(min(m, n))) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(log(min(m, n)))Space O(1)
The optimal approach uses binary search to find the correct partition of the two arrays. This allows us to find the median in O(log(min(m, n))) time, which is much faster than merging the arrays.
⚙️
Algorithm
5 steps- 1Step 1: Ensure nums1 is the smaller array. If not, swap them.
- 2Step 2: Initialize binary search on the smaller array.
- 3Step 3: Calculate partitions for both arrays based on the current binary search index.
- 4Step 4: Check if the partitions are valid (maxLeft1 <= minRight2 and maxLeft2 <= minRight1).
- 5Step 5: If valid, calculate the median based on the total length (odd/even). If not, adjust the binary search bounds.
solution.py27 lines
1# Full working Python code with comments
2
3def findMedianSortedArrays(nums1, nums2):
4 if len(nums1) > len(nums2):
5 nums1, nums2 = nums2, nums1
6 x, y = len(nums1), len(nums2)
7 low, high = 0, x
8 while low <= high:
9 partitionX = (low + high) // 2
10 partitionY = (x + y + 1) // 2 - partitionX
11 maxLeftX = float('-inf') if partitionX == 0 else nums1[partitionX - 1]
12 minRightX = float('inf') if partitionX == x else nums1[partitionX]
13 maxLeftY = float('-inf') if partitionY == 0 else nums2[partitionY - 1]
14 minRightY = float('inf') if partitionY == y else nums2[partitionY]
15 if maxLeftX <= minRightY and maxLeftY <= minRightX:
16 if (x + y) % 2 == 0:
17 return (max(maxLeftX, maxLeftY) + min(minRightX, minRightY)) / 2.0
18 else:
19 return max(maxLeftX, maxLeftY)
20 elif maxLeftX > minRightY:
21 high = partitionX - 1
22 else:
23 low = partitionX + 1
24
25# Example usage
26print(findMedianSortedArrays([1, 3], [2])) # Output: 2.0
27print(findMedianSortedArrays([1, 2], [3, 4])) # Output: 2.5ℹ
Complexity note: The time complexity is O(log(min(m, n))) because we are performing binary search on the smaller array. The space complexity is O(1) since we are using a constant amount of space for variables.
- 1The key observation is that the median can be found by partitioning the two arrays such that all elements on the left are less than or equal to all elements on the right.
- 2Another important insight is that we can leverage binary search to efficiently find the correct partition, which reduces the time complexity significantly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.