Introduction
In this blog post, we will dive into an interesting coding problem: finding the median of two sorted arrays. We will explore a specific implementation of this problem and dissect each step to understand its functionality. So, let’s get started!
Given two sorted arrays A
and B
of size m
and n
respectively, return the median of the two sorted arrays.
Discussion
Step 1 – Handling Array Lengths
To ensure simplicity and efficiency, we begin by comparing the lengths of the given arrays, A
and B
. If array A
is longer than array B
, we swap the arrays and their corresponding lengths. This step sets the stage for further calculations.
Step 2 – Initializing Variables
To facilitate the binary search approach, we initialize a few variables. These include iMin
and iMax
, representing the minimum and maximum indices for the binary search. Additionally, we calculate halfLen
, which determines the midpoint of the combined arrays.
Step 3 – Binary Search Loop
The core of our implementation lies within a while loop, which continues until the search space is exhausted. This binary search approach allows efficient exploration of the possibilities to find the median of the combined arrays.
Step 4 – Updating Split Positions
Within the loop, we calculate the indices i and j, representing the split positions in arrays A
and B
, respectively. These split positions divide the arrays into left and right parts, which play a crucial role in finding the median.
Step 5 – Adjusting iMin
and iMax
Based on the values of A[i]
, B[j]
, A[i - 1]
, and B[j - 1]
, we determine whether i
is too small or too big. If B[j - 1]
is greater than A[i]
, it implies that i
is too small, so we update iMin
to search the right half of the search space. Conversely, if A[i - 1]
is greater than B[j]
, it means that i
is too big, so we update iMax
to search the left half of the search space.
Step 6 – Finding the Perfect Split
If neither of the conditions from Step 5 is met, it indicates that i
is the perfect split position. At this stage, we find the maximum element on the left side of the split. This maximum, denoted as maxLeft
, is determined based on the values of A[i - 1]
and B[j - 1]
. This step ensures that we have the necessary information to calculate the median.
Step 7: Handling Odd and Even Number of Elements
We need to handle scenarios where the total number of elements, (m + n)
, is odd or even. If it is odd, we return maxLeft
as the median since it represents the middle element. However, if the total number is even, we find the minimum element on the right side of the split. This minimum, denoted as minRight
, is calculated based on the values of A[i]
and B[j]
.
Step 8: Calculating the Median
With both maxLeft
and minRight
determined, we calculate the median by taking their average. This step ensures an accurate representation of the central value when there is an even number of elements in the combined arrays.

Here is the implementation
public static double findMedianSortedArrays(int[] A, int[] B){
int m = A.length;
int n = B.length;
if(m > n){
int [] temp = A;
A = B;
B = temp;
int tmp = m; m = n; n = tmp;
}
int iMin = 0, iMax = m, halfLen = ( m + n + 1) / 2;
while (iMin <= iMax){
int i = (iMin + iMax) / 2;
int j = halfLen - i;
if (i < iMax && B[j - 1] > A[i]){
iMin = i + 1; // i is too small
}
else if (i > iMin && A[i - 1] > B[j]) {
iMax = i - 1; // i is too big
}
else { // i is perfect
int maxLeft;
if (i == 0){
maxLeft = B[j - 1];
}else if (j == 0){
maxLeft = A[i -1];
}
else {
maxLeft = Math.max(A[i - 1], B[j - 1]);
}
if ((m+n) % 2 == 1){
return maxLeft;
}
int minRight;
if (i == m){
minRight = B[j];
} else if (j == n) {
minRight = A[i];
}else {
minRight = Math.min(B[j],A[i]);
}
return (maxLeft + minRight) / 2.0;
}
}
return 0.0;
}
Time Complexity:
The time complexity of the code is O(log(min(m, n))), where m and n are the lengths of arrays A
and B
, respectively. The code uses a binary search approach to find the median, repeatedly dividing the search space in half until the median is found or the search space is exhausted. Since the search space is reduced by half in each iteration, the time complexity is logarithmic.
Space Complexity:
The space complexity of the code is O(1). The code only uses a few variables for indices and temporary storage, all of which require constant space. It does not use any additional data structures that grow with the size of the input arrays.
Overall, the code has an efficient time complexity of O(log(min(m, n))) and a constant space complexity of O(1).
Conclusion
In this blog post, we explored the step-by-step process of finding the median of two sorted arrays. By handling array lengths, utilizing a binary search loop, updating split positions, and performing necessary calculations, we can efficiently determine the median value. Now, let’s dive into the implementation and witness these steps in action.
We’re excited to share that we have an engaging Facebook and YouTube page where we regularly post informative and insightful content. Our previous posts cover a wide range of topics, including coding challenges, algorithm explanations, and programming tips. Join our community on Facebook and subscribe to our YouTube channel to stay updated with our latest posts and enrich your coding journey!