Median of Two Sorted Arrays
Last updated
Last updated
Given two sorted arrays, find the median of the these two arrays.
There two cases 1. the total length is even 2. the total length is odd
The intuitive approach is merging these two arrays. Then compute the median base on the total length. We need O(m+n) time and O(m+n) space for this very brute force approach. We can refine it by counting to the half the total length. This refined brute force will take O((m+n)/2) time and O(1) space.
In order do better than linear time, we need to decompose the search space. Then we need to have two things in hand: 1. define a well-ordered search space 2. create a O(1) validator to reset the interval. If you think really hard on creating a nice search space, then the validator will be easy to create. If you just take the problem space as the search space, then the the creation of the validator requires some thinking.
Consider median as a specical case of find the kth largest element. Then the problem becomes (int[] sortedArr1, int[] sortedArr2, int k) => kth largest element
We can performa a binary search on k and modify the search space (halve the search target instead of the search space).
Distribute the load between two arrays k/2 to arr1 and k/2 to arr2
What if an array is too small? then dump the longer one because we are not sure about the how small/how large are the elements in the smaller array.
The time complexity is O(logk) = O(log((n+m)/2)) = O(log(n+m))
. Since the deleting operation only involves pointer movements, the space complexity is O(1).
The other way is separating arr1
and arr2
into 2 sets that satisfy the definition of the median. The validator will take a long time to come up with to handle all the possible cases.