Reputation: 2079
Please suggest a data structure to maintain numbers in such a way that i can answer the following queries -
Find(int n) - O(log(n))
Count number of numbers less than k = O(log(n))
Insert - O(Log(n))
It's not homework, but a smaller problem that i am encountering to solve a bigger one - Number of students with better grades and lower jee rank
I have though of an avl tree with maintaining number of nodes in subtree at each nod.But i dont know how to maintain this count at each node when an insert is being done and re-balancing is being done.
Upvotes: 2
Views: 227
Reputation: 10658
I would also try using an AVL Tree. Without looking much deeper into it, I don't think this would be too hard to add. In case of an AVL tree you alway need to know the depth of each subtree for each node anyway (or at least the balancing factor). So it should not be too hard to propagate the size of the subtrees. In case of an rotation, you know exactely where each node and each subtree will land, so it should be just a simple recalculation for those nodes, which are rotated.
Upvotes: 1
Reputation: 7414
Have a look at the different variants of heap data structures, e.g. here.
Upvotes: -1
Reputation: 109567
Finding in a binary tree is O(log(n)), inserting too. If you store the subtree size in the node:
So subtree size is like a find, O(log(n)).
Upvotes: 1