This is an interview question. Design a class, which stores integers and provides two operations:
void insert(int k) int getMedian()
I guess I can use BST so that insert takes O(logN) and getMedian takes O(logN) (for getMedian I should add the number of of left/right children for each node).
Now I wonder if this is the most efficient solution and there is no better one.
You can use 2 heaps, that we will call
LeftandRight.Leftis aMax-Heap.Rightis aMin-Heap.Insertion is done like this:
xis smaller than the root ofLeftthen we insertxtoLeft.xtoRight.Lefthas count of elements that is greater than 1 from the count of elements ofRight, then we call Extract-Max onLeftand insert it toRight.Righthas count of elements that is greater than the count of elements ofLeft, then we call Extract-Min onRightand insert it toLeft.The median is always the root of
Left.So insertion is done in
O(lg n)time and getting the median is done inO(1)time.