Problem
There are two sorted arrays nums1 and nums2 of size n. Find the median of the two sorted arrays.
You may assume nums1 and nums2 cannot be both empty.
OR There are 2 sorted arrays A and B. Write an algorithm to find the median of the array obtained after merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n))
Median Definition
Note → Since the size of the two input arrays for which we are looking for the median is even(2n), we need to take the average of the middle two numbers and return it.
Examples
Example 1:
| |
| |
Example 2:
| |
| |
Solution
Method 1 - Brute Force
We can combine two arrays into a sorted array in O(n) time and then calculate the average of the middle two values. However, this approach is not efficient enough.
Method 2 - Counting While Comparing (kind of Brute force)
- Initialise two pointers,
iandj, to 0, pointing to the start ofnums1andnums2, respectively. - Compare the values at
nums1[i]andnums2[j]; ifnums1[i]is smaller, incrementi; otherwise, incrementj. - Continue step 2 until the sum of
iandjequalsn. - Finally, return the median of the elements at the
i-thandj-thindexes.
Code
| |
Complexity
- ⏰ Time complexity:
O(n)wherenis the size of the input arrays - 🧺 Space complexity:
O(1)
Method 3 - Comparing Medians - Divide and Conquer
This method involves comparing the medians of both arrays using the Divide & Conquer approach. Let us denote the medians by m1 and m2.
- If
m1 > m2, then the median will be in the union ofnums1[0 to m1]andnums2[m2 to n]. This means we search for the median withinnums1from the beginning tomedian1and withinnums2frommedian2to the end. (Why?)
To sum up:
| |
We know median1 is at least as large as the first half of nums1, and similarly for median2 and nums2. We also know median1 is at most as large as the second half of nums1.
Consider the case where median1 > median2:
| |
Example
| |
| |
| |
| |
| |
Algorithm
Calculate the medians
m1andm2ofnum1[]andnum2[].Repeat until the size of
num1andnum2is two.- If
m1 == m2, return m1. - If
m1 > m2, the median is innum1[0..m1]andnum2[m2 to n]. - If
m2 > m1, the median is innum1[m1 to n]andnum2[0 to m2].
- If
Return
Median = (max(array1[0], array2[0]) + min(array1[1], array2[1])) / 2.
Code
| |
Complexity
- ⏰ Time complexity:
O(log n), wherenis length of array, as we compare the medians of the two arrays and then recursively reduce the problem size. - 🧺 Space complexity:
O(log n), assuming recursion stack