This excerpt is from Cracking the Coding Interview 5th Edition
Numbers are randomly generated and stored in an (expanding) array. How would you keep track of the median
The author walked us through a solution based on heaps:
A heap is really good at basic ordering and keeping track of max and mins. This is actually interesting - if you could keep track of the bigger half and the smaller half of the elements. The bigger half is kept in a min heap, such that the smallest element in the bigger half is at the root. The smaller half is kept in a max heap such that the biggest element of the smallest half is at the root. Now with these data structures, you have the potential median elements at the root." If the heaps are no longer the same size, you can quickly "rebalance" the the heaps by popping an element off the heap and pushing it to the onto the other
I have a couple questions about this approach by I ask them one at a time to keep it organized. First of all, using this approach, if you iterate through the elements in the array, how would you know a specific element belongs in the min heap or the max heap as described by the algorithm? Say our data elements are [20, 39, 14, 7, 86, 90]. When you iterate the array, what heap would you put, lets say 20?