Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a sorted data structure with logarithmic time insertion, deletion and find (with distance)?

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?

like image 686
CCD Avatar asked Feb 09 '19 08:02

CCD


Video Answer


2 Answers

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.

like image 134
ruakh Avatar answered Oct 05 '22 23:10

ruakh


You can use balanced BST with size of left subtree in each node to calculate distance

like image 27
Prerna Jain Avatar answered Oct 05 '22 22:10

Prerna Jain