Reputation: 73
I have a sorted array in which I find number of items less than particular value using binary search (std::upper_bound
) in O(logn)
time.
Now I want to insert and delete from this array while keeping it sorted. I want the overall complexity to be O(logn)
.
I know that using binary search tree or std::multiset
I can do insertion, deletion and upper_bound in O(logn)
but I am not able do get the distance/index (std::distance
is O(n)
for sets) in logarithmic time.
So is there a way to achieve what I want to do?
Upvotes: 6
Views: 1180
Reputation: 21
You can use balanced BST with size of left subtree in each node to calculate distance
Upvotes: 1
Reputation: 183241
You can augment any balanced-binary-search-tree data structure (e.g. a red-black tree) by including a "subtree size" data-member in each node (alongside the standard "left child", "right child", and "value" members). You can then calculate the number of elements less than a given element as you navigate downward from the root to that element.
It adds a fair bit of bookkeeping, and of course it means you need to use your own balanced-binary-search-tree implementation instead of one from the standard library; but it's quite doable, and it doesn't affect the asymptotic complexities of any of the operations.
Upvotes: 7