Median of Two Sorted Arrays (LeetCode 4): Solution and Explanation
Given two sorted arrays, return the median of all their elements combined, as if they were merged into one sorted array. The target running time is logarithmic in the array sizes.
Watch it run step by step
Try your own input and write the code →Intuition
The direct approach merges the two arrays with two pointers, like the merge step of merge sort, and reads the middle element or elements. That is O(m + n). You can stop the merge halfway, but it is still linear. To get to logarithmic time you have to avoid building the merged array at all.
Think about what the median really means. It splits the combined elements into a left half and a right half of equal size (or with one extra on the right for odd totals), where everything on the left is at most everything on the right. That left half is made of some prefix of A and some prefix of B. If you take i + 1 elements from A, you must take exactly half - (i + 1) elements from B. So choosing the cut in A determines the cut in B, and the problem becomes finding the right single cut.
A cut is valid when the largest left value of A is at most the smallest right value of B, and the largest left value of B is at most the smallest right value of A. If A's left side is too big (Aleft > Bright), you took too many from A, so move the cut left. Otherwise you took too few, so move it right. That is a binary search on the cut position in A, and running it on the shorter array keeps it at O(log(min(m, n))) and keeps the B index in range.
Empty sides are handled with infinities: a cut before the first element has a left value of negative infinity, and a cut after the last has a right value of positive infinity. Once the cut is valid, the median is the smaller right value for an odd total, or the average of the larger left value and the smaller right value for an even total.
Approach: Binary search on the partition
- Let
Abe the shorter array andBthe longer, and computetotalandhalf = total // 2. - Binary search over
i, the index of the last element of A in the left half, withl = 0andr = len(A) - 1. - Set
j = half - (i + 1) - 1, the last index of B in the left half. - Read
Aleft,Aright,BleftandBright, substituting negative or positive infinity when an index is out of range. - If
Aleft <= BrightandBleft <= Aright, the partition is valid: returnmin(Aright, Bright)for an odd total, or the average ofmax(Aleft, Bleft)andmin(Aright, Bright)for an even total. - If
Aleft > Bright, move left withr = i - 1; otherwise move right withl = i + 1.
Step-by-step example
nums1 = [1,2], nums2 = [3,4]
- Both arrays have length 2, so no swap happens.
total= 4 andhalf= 2. - First guess:
i= 0, soj= 2 - 1 - 1 = 0.Aleft= 1,Aright= 2,Bleft= 3,Bright= 4. Bleft= 3 is greater thanAright= 2, so too few elements came from A. Move right withl= 1.- Next
i= 1 andj= -1.Aleft= 2,Aright= +∞,Bleft= -∞,Bright= 3. Both conditions hold. - The total is even, so the median is (max(2, -∞) + min(+∞, 3)) / 2 = (2 + 3) / 2 = 2.5.
Code: Python, Java, C++
1class Solution:
2 def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
3 A, B = nums1, nums2
4 total = len(nums1) + len(nums2)
5 half = total // 2
6
7 if len(B) < len(A):
8 A, B = B, A
9
10 l, r = 0, len(A) - 1
11 while True:
12 i = (l + r) // 2
13 j = half - (i + 1) - 1
14
15 Aleft = A[i] if i >= 0 else float("-infinity")
16 Aright = A[i + 1] if (i + 1) < len(A) else float("infinity")
17 Bleft = B[j] if j >= 0 else float("-infinity")
18 Bright = B[j + 1] if (j + 1) < len(B) else float("infinity")
19
20 if Aleft <= Bright and Bleft <= Aright:
21 if total % 2:
22 return min(Aright, Bright)
23 return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
24 elif Aleft > Bright:
25 r = i - 1
26 else:
27 l = i + 11class Solution {
2 public double findMedianSortedArrays(int[] nums1, int[] nums2) {
3 int[] A = nums1;
4 int[] B = nums2;
5 int total = nums1.length + nums2.length;
6 int half = total / 2;
7
8 if (B.length < A.length) {
9 int[] temp = A; A = B; B = temp;
10 }
11
12 int l = 0, r = A.length - 1;
13 while (true) {
14 int i = (int)Math.floor((l + r) / 2.0);
15 int j = half - (i + 1) - 1;
16
17 double Aleft = i >= 0 ? A[i] : Double.NEGATIVE_INFINITY;
18 double Aright = (i + 1) < A.length ? A[i + 1] : Double.POSITIVE_INFINITY;
19 double Bleft = j >= 0 ? B[j] : Double.NEGATIVE_INFINITY;
20 double Bright = (j + 1) < B.length ? B[j + 1] : Double.POSITIVE_INFINITY;
21
22 if (Aleft <= Bright && Bleft <= Aright) {
23 if (total % 2 != 0) return Math.min(Aright, Bright);
24 return (Math.max(Aleft, Bleft) + Math.min(Aright, Bright)) / 2.0;
25 } else if (Aleft > Bright) {
26 r = i - 1;
27 } else {
28 l = i + 1;
29 }
30 }
31 }
32}1class Solution {
2public:
3 double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
4 vector<int>& A = nums1;
5 vector<int>& B = nums2;
6 int total = nums1.size() + nums2.size();
7 int half = total / 2;
8
9 if (B.size() < A.size()) swap(A, B);
10
11 int l = 0, r = A.size() - 1;
12 while (true) {
13 int i = floor((l + r) / 2.0);
14 int j = half - (i + 1) - 1;
15
16 double Aleft = i >= 0 ? A[i] : -DBL_MAX;
17 double Aright = (i + 1) < A.size() ? A[i + 1] : DBL_MAX;
18 double Bleft = j >= 0 ? B[j] : -DBL_MAX;
19 double Bright = (j + 1) < B.size() ? B[j + 1] : DBL_MAX;
20
21 if (Aleft <= Bright && Bleft <= Aright) {
22 if (total % 2) return min(Aright, Bright);
23 return (max(Aleft, Bleft) + min(Aright, Bright)) / 2.0;
24 } else if (Aleft > Bright) {
25 r = i - 1;
26 } else {
27 l = i + 1;
28 }
29 }
30 }
31};Time and space complexity
O(log(min(m, n)))
The binary search runs only over the shorter array, and each step does constant work to compute the cut in the longer one.
O(1)
Only indices and four boundary values are stored.
Other approaches
Two-pointer merge (time O(m + n), space O(1))
Walk both arrays with two pointers as in merge sort and stop when you reach the middle position, tracking the last one or two values seen. It is easy to get right and is fine when linear time is acceptable.
K-th element by elimination (time O(log(m + n)), space O(log(m + n)))
Find the k-th smallest element of the union recursively by comparing the k/2-th elements of each array and discarding the smaller half. Calling it once or twice gives the median. It generalizes to any order statistic.
Common mistakes
- Binary searching on the longer array, which can push
jout of range and makes the boundary handling much harder. - Forgetting the infinity sentinels for cuts at the very start or end of an array, which leads to index errors on inputs like one empty array.
- Using the wrong side for an odd total. With
half = total // 2elements on the left, the extra element is on the right, so the median ismin(Aright, Bright). - Computing the midpoint with truncating division. When
rdrops to -1, the code needsi= -1, meaning A contributes nothing to the left half. Python's//floors to -1, but plain integer division in Java or C++ gives 0, which is why those versions callfloorexplicitly.
Frequently asked questions
Why do we binary search on the smaller array?
It limits the search to O(log(min(m, n))) steps and guarantees that the matching cut in the larger array always lands within its bounds.
How does the partition approach find the median?
It looks for a cut in each array so the combined left side has half the elements and every value on the left is at most every value on the right. The median then comes from the values adjacent to the cut.
Can I just merge the arrays?
Merging gives the right answer in O(m + n) time and is a reasonable first solution. The logarithmic partition method is what an interviewer expects for this hard problem.
What happens if one array is empty?
The empty array becomes A, its cut values are all infinities, and the condition holds right away. The median is then read directly from the middle of the other array.