Prompt:
"Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n))."
I'm ashamed to admit that this wasn't my best attempt at solving a problem, with my runtime clocking in about about 111ms (the average being around 99-100ms). I owe this to approaching the problem too concretely, since the point of the question was to find a specific solution and I focused too much on the idea of creating and manipulating an array when I could've just used an existing algorithm (like one of the proposed solutions, reliable old merge sort).
Let's do an analysis of my answer (in TypeScript).
function findMedianSortedArrays(nums1: number[], nums2: number[]): number {
let nums3: number[] = []
let ans: number
while((nums1.length > 0) && (nums2.length > 0)){
if(nums1[0] < nums2[0]){
nums3.push(nums1.shift())
} else {
nums3.push(nums2.shift())
}
}
while(nums1.length > 0){
nums3.push(nums1.shift())
}
while (nums2.length > 0) {
nums3.push(nums2.shift())
}
if (nums3.length%2 == 0){
ans = (((nums3[(nums3.length/2) - 1]) + (nums3[(nums3.length/2)]))/2)
} else {
ans = nums3[(nums3.length/2) - .5]
}
return ans
};
Let's go line-by-line and try to calculate the Big O complexity to see if it comes anywhere close to the required O(log(m+n)):
The initial assignments have a constant time complexity of O(1), as they don't require any operations in and of themselves.
The initial while
loop
while((nums1.length > 0) && (nums2.length > 0))
has a complexity of O(m+n), as the operation continues for the length of both of the arrays; that being said, extreme cases, such as a case where one of the arrays is entirely smaller than the values of the other array and the loop ends with only one array depleted. As such, the complexity would be the length of the depleted array, being O(m) or O(n).
The shifts within the first while loop are enclosed within an if-else statement that will run with every loop; this if-else will therefore have a complexity equivalent to the while statement. The shift methods within the if-else statement will also have a complexity of O(m+n), since shift operations require the re-indexing of every subsequent index value (so shifting 1 out of the list 1,2,3 would require that 2 and 3 are individually moved back).
The second and third while
statements similarly run for the length of their respective arrays' remaining length, and the assignments for the return statement (as well as the return statement itself) are all O(1).
The resulting complexity simplifies to O(m+n), which is much slower than the target of O(log (m+n)). Magical.