Median of Two Sorted Arrays of Different Sizes (Binary Search Approach)
1. Problem Statement & Status Quo
Given two sorted arrays, arr1 and arr2, of potentially different sizes ( and ), our objective is to find the median of the combined elements.
Why the Naive Approach Fails
- Naive Strategy: Merge both sorted arrays into a single sorted array of size , then pick the middle element (for odd total length) or average the two middle elements (for even total length).
- Time Complexity: because we must traverse and combine all elements.
- Production Bottleneck: This linear approach causes Time Limit Exceeded (TLE) errors in competitive programming and high-performance interviews when and are massive. We need an optimized logarithmic approach.
2. Core Mental Model: The Symmetry Approach
Since both arrays are already sorted, we can harness Binary Search to achieve an time complexity.
Instead of physically merging arrays, we visualize a hypothetical combined sorted array and draw a symmetry line right down the middle to divide it into a left half and a right half.
Real-Life Analogy: Splitting a Line of People by Height
Imagine lining up two separate rows of people, each already sorted by height. To divide them into two equal groups (a left group and a right group) without fully merging the rows, you decide how many people to take from Row 1. Once you pick people from Row 1, the exact number of people needed from Row 2 is automatically locked in to satisfy the total size of the left half. If the tallest person in the left group from either row is shorter than or equal to the shortest person in the right group, you have successfully formed a valid split!
3. Step-by-Step Evolution of Left/Right Partitions
Let's examine an example where:
arr1length :[1, 3, 4, 7, 10, 12]arr2length :[2, 3, 6, 15]- Total Elements: (Even)
- Required Left Half Size: elements.
Testing Partition Candidates for Array 1
- Pick 0 from Array 1:
- Need from Array 2 (impossible since Array 2 only has 4 elements). Invalid
- Pick 1 from Array 1:
- Pick from Array 2.
- Left:
[1] (from arr1),[2, 3, 6, 15] (from arr2) - Right:
[3, 4, 7, 10, 12] - Check: Maximum on left () is greater than minimum on right (). Invalid Symmetry
- Pick 2 from Array 1:
- Left:
[1, 3],[2, 3, 6] - Check: Max element on left () > Min element on right (). Invalid Symmetry
- Left:
- Pick 3 from Array 1:
- Left:
[1, 3, 4](3 elements fromarr1),[2, 3](2 elements fromarr2) - Right:
[7, 10, 12](fromarr1),[6, 15](fromarr2) - Check:
- Max left elements: (from
arr1), (fromarr2) - Min right elements: (from
arr1), (fromarr2) - Is entire left smaller than entire right? Yes ( and ). Valid Symmetry!
- Max left elements: (from
- Left:
4. Validating the Symmetry (The Cross-Check Rule)
Once we pick elements from arr1 and elements from arr2 (where ), we define four boundary pointers:
Array 1: [... L1 ] | [ R1 ...]
Array 2: [... L2 ] | [ R2 ...]
- : Last element included on the left from
arr1(arr1[mid_1 - 1]) - : First element on the right from
arr1(arr1[mid_1]) - : Last element included on the left from
arr2(arr2[mid_2 - 1]) - : First element on the right from
arr2(arr2[mid_2])
The Validation Condition
A partition is valid if and only if:
Note: We do not need to compare with or with because each individual array is already internally sorted. We only need to check the cross-arrays.
5. Formulating the Median
Once a valid symmetry is established, extracting the median depends on whether the total number of elements () is Even or Odd.
Case A: Even Number of Elements
If total elements , the median is the average of the maximum element on the left and the minimum element on the right:
Case B: Odd Number of Elements
If total elements , we define the left partition size as .
6. Binary Search Optimization Strategy
To achieve logarithmic time complexity, we must perform our binary search on the smaller array (arr1).
Adjustment Rules (Binary Search Pointers)
- If : Elements taken from
arr1are too large. We need to move our search space to the left (high = mid1 - 1). - If : Elements taken from
arr1are too small. We need to move our search space to the right (low = mid1 + 1).
7. Complete Code Implementation (C++)
#include <vector>
#include <algorithm>
#include <climits>
class Solution {
public:
double findMedianSortedArrays(std::vector<int>& nums1, std::vector<int>& nums2) {
// Ensure nums1 is the smaller array to optimize binary search range
if (nums1.size() > nums2.size()) {
return findMedianSortedArrays(nums2, nums1);
}
int n1 = nums1.size();
int n2 = nums2.size();
int low = 0, high = n1;
int leftSize = (n1 + n2 + 1) / 2;
while (low <= high) {
int mid1 = low + (high - low) / 2;
int mid2 = leftSize - mid1;
// Calculate L1, L2, R1, R2 with boundary edge cases
int l1 = (mid1 == 0) ? INT_MIN : nums1[mid1 - 1];
int l2 = (mid2 == 0) ? INT_MIN : nums2[mid2 - 1];
int r1 = (mid1 == n1) ? INT_MAX : nums1[mid1];
int r2 = (mid2 == n2) ? INT_MAX : nums2[mid2];
// Check if we found the valid symmetry
if (l1 <= r2 && l2 <= r1) {
// If total elements are odd
if ((n1 + n2) % 2 == 1) {
return std::max(l1, l2);
}
// If total elements are even
return (double)(std::max(l1, l2) + std::min(r1, r2)) / 2.0;
}
// If l1 is too large, move left
else if (l1 > r2) {
high = mid1 - 1;
}
// If l2 is too large, move right
else {
low = mid1 + 1;
}
}
return 0.0;
}
};
8. Complexity Analysis
9. Summary and Key Takeaways
- Problem Nature: Finding the median of two sorted arrays can be reframed as finding a correct partition symmetry where the left half elements are smaller than or equal to the right half elements.
- Binary Search on Smaller Array: Always execute binary search on the smaller array (
min(N_1, N_2)) to guarantee optimal performance. - Dynamic Partitioning:
mid_1determines the cut on the first array, whilemid_2is statically derived from the total left partition size requirement ((N1 + N2 + 1) / 2 - mid1). - Edge Value Handling: Use
INT_MINfor out-of-bound left elements andINT_MAXfor out-of-bound right elements to ensure cross-comparisons never fail on array boundaries. - Parity Handling: Odd total element counts return , while even total element counts average and .
- Space Optimization: Avoiding physical array merging reduces auxiliary space consumption to absolute zero ( space).