See the original problem on HackerRank.
This is a classical problem whose typical solution involves employing two (differently ordered) heaps that maintain the two halves of the input arranged in a way that is convenient to retrieve the maximum of the former and the minimum of the latter. In other words, Consider this sample input:


Imagine we want to calculate the median of this array. We can see the array as:


If both the subarrays are, respectively, a max heap and a min heap, we have a quick way to retrieve the largest element of the left side and the smallest of the right side, thus the median is given by the average of the top elements of both the heaps.
If the size of the array is odd, we will end up having one heap that is longer. The top of that heap is the median.
To do this, we should keep the two heaps sort of balanced, that is: they should never have a size that differs by more than one element.
In addition, this approach is good for solving the problem online (in streaming). In fact, we don’t really need to read all the input in advance.
The most common data structure to solve this problem efficiently is a priority queue which uses a heap underneath. The overall complexity is \(O(N \cdot logN)\) Here is a C++ solution:


The code above might be splitted into separate functions to make the algorithm clearer.
Alternatively, fullysorted data structures such as sorted vectors, sets or maps could be employed to keep the “window” sorted. Although this approach works on every test case, it constitues a suboptimal solution. For example:


This solution is quadratic, as insert
ing each element potentially causes all the window’s elements to be moved.
Another implementation of this approach in Python was done by Andrea Naletto:


As pointed out in the comment, bisect.insort()
is linear because the logarithmic search step is dominated by the linear time insertion step. This means, the solution is quadratic (just like the other above).