Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash table in C++

Tags:

c++

hashtable

map

Is the insertion/deletion/lookup time of a C++ std::map O(log n)? Is it possible to implement an O(1) hash table?

like image 213
Paul S. Avatar asked Oct 12 '12 20:10

Paul S.


2 Answers

Is the insertion/deletion/lookup time of a C++ map O(log n)?

Yes.

Is it possible to implement an O(1) hash table?

Definitely. The standard library also provides one as std::unordered_map.

like image 158
Kos Avatar answered Sep 19 '22 21:09

Kos


C++ has a unordered_map type. The STL also contains a hash_map type, although this is not in the C++ standard library.

Now, for a bit of algorithmic theory. It is possible to implement an O(1) hash table under perfect conditions, and technically, hash tables are O(1) insertion and lookup. The perfect conditions in this case are that the hash function must be perfect (i.e. collision free), and you have infinite storage.

In practise, let's take a dumb hash table. For any input key, it returns 1. In this case, when there is a collision (i.e. on the second and subsequent insertions), it will have to chain further to find some free space. It can either go to the next storage location, or use a linked list for this.

In any case, in the best case, yes, hash tables are O(1) (until you have exhausted all of your hash values, of course, since it is impractical to have a hash function with an infinite amount of output). In the worst case (e.g. with my completely dumb hash function), hash tables are O(n), since you will have to traverse over the storage in order to find your actual value from the given hash, since the initial value is not the correct value.

like image 32
slugonamission Avatar answered Sep 19 '22 21:09

slugonamission