Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data structure with O(1) insertion and O(log(n)) search complexity?

Is there any data structure available that would provide O(1) -- i.e. constant -- insertion complexity and O(log(n)) search complexity even in the worst case?

A sorted vector can do a O(log(n)) search but insertion would take O(n) (taken the fact that I am not always inserting the elements either at the front or the back). Whereas a list would do O(1) insertion but would fall short of providing O(log(n)) lookup.

I wonder whether such a data structure can even be implemented.

like image 954
Chirag Arora Avatar asked Nov 05 '16 12:11

Chirag Arora


People also ask

Can we perform insertion in O 1 time complexity?

Worst time complexity for inserting into list is O(n-i) , where n is the length of the list and i is the index at which you are inserting. So in case if you are inserting at the last index, that makes it O(1) .

Which data structure has an O n worst case search complexity?

Linear Search The average to the worst case of this kind of search is a linear complexity or O(n).

Which data structure has efficient search time?

For efficient searching, one would definitely prefer a binary search tree.


1 Answers

Yes, but you would have to bend the rules a bit in two ways:

1) You could use a structure that has O(1) insertion and O(1) search (such as the CritBit tree, also called bitwise trie) and add artificial cost to turn search into O(log n).

A critbit tree is like a binary radix tree for bits. It stores keys by walking along the bits of a key (say 32bits) and use the bit to decide whether to navigate left ('0') or right ('1') at every node. The maximum complexity for search and insertion is both O(32), which becomes O(1).

2) I'm not sure that this is O(1) in a strict theoretical sense, because O(1) works only if we limit the value range (to, say, 32 bit or 64 bit), but for practical purposes, this seems a reasonable limitation.

Note that the perceived performance will be O(log n) until a significant part of the possible key permutations are inserted. For example, for 16 bit keys you probably have to insert a significant part of 2^16 = 65563 keys.

like image 180
TilmannZ Avatar answered Oct 04 '22 08:10

TilmannZ