Coding interview: Find median of 2 sorted arrays of int part 1

You are given 2 array of integers as input. They are sorted. Write a function can find the median of all the numbers.

First need to clarify what is median. When given a bunch of numbers, if you sort them, the number right in the middle is called the median. For example if we have [1, 2, 3, 4, 8, 9], the median is 4. When we have even number of numbers, it is the mean of those two in the middle. For example if we have [1, 2, 3, 4, 8, 9, 10], then the median is (4+8)/2=6

Next let’s solve the problem with a simple direct and easy to understand solution:

Really simple, right? And we are very sure it is correct as long as the merge function and median function are correct. Well you probably will be asked to implement them during an interview so here is one version:

Now, what is the problem with this approach? If you say it is too slow then you probably know the speed of the solution is O(m+n) which is linear. And you are right that we can do better than that but there are problems other than time. The action of merge array uses O(m+n) space which we can also avoid. But the bigger problem is that when we try to allocated the space for array c, we may not able to because m+n may overflow, same reason that I had to do the trick when I try to find the median. So let’s avoid it and avoid allocate a new array all together in part 2