Pergunta de entrevista da empresa Google

design a structure have these two functions: insert, getMedian, discuss the time complexity

Respostas da entrevista

Sigiloso

13 de abr. de 2010

use a self balancing binary search tree (BST) that has the same size (or off by one) left and right subtrees from the root getMedian: O(1) since the tree is balanced the median will always be the root node insert: O(logN) BST gives us logN insertion, balancing the tree is O(logN) as well and works in the following way: (this is only the most difficult case) if upon insertion the left subtree has two more nodes then the right subtree we need to rebalance the BST, that is take the largest value on the left subtree (rightmost node) and make that the new root, that works fine as this value is greater than everything on the left subtree and less than everything on the right subtree, then take the old root value and insert it in the right subtree, then the tree is balanced again and the median value is the root, ta-da! :)

4

Sigiloso

19 de jan. de 2011

I am not sure that the median is in root. You can draw a tree that is balanced ( the depth of the left child - the depth of the right child <= 1). Then it is very hard to see which is the element. You can solve this problem by using 2 heaps: - one max-heap for the 1/2 lowest elements; - one min-heap for the 1/2 highest elements; On insertion, you can insert in heap and balance the heap (if the difference of the sizes is greater than 1, then remove the maximum (minimum) from one and insert to another). This is done in O(log n). When you get the median if the sizes of these 2 heaps are the same, then take the average of the max (min) heaps, otherwise, return the element from top of the heap with the highest number of elements.