Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hash table lookup time

Tags:

hashtable

When we are insert/lookup an key in a hash table, textbook said it is O(1) time. Yet, how is possible to have an O(1) lookup time? If the hash table store the key in a vector, it will cost O(N), if in a binary tree, it will be O(logN). I just can't image some data structure with O(1) accessing time.

Thanks!

like image 874
Mark5907 Avatar asked Jan 17 '13 05:01

Mark5907


People also ask

What is the time complexity for hash table lookup?

The hash key is calculated in O(1) time complexity as always, and the required location is accessed in O(1). Insertion: In the best case, the key indicates a vacant location and the element is directly inserted into the hash table. So, overall complexity is O(1).

Why does searching a lookup table take O 1 time?

You're missing the most important "feature" of a hash table, which is that the hash code of the key is used to map the key to a position in the array of buckets. So, given a key, finding the index in the array of buckets takes a constant time (given the hash code calculation is based only on the the value of the key).

Why is hash lookup fast?

The reason for this is that there are more hash collisions when the table is more full. So you can see the cost go up until at some point the table decides that it's too full and that it should reallocate, which makes lookups fast again.

What is hash table lookup?

The Hash Lookup Function obtains the value for a destination column from a lookup table, according to a hashed value derived from a source column. The Hash Lookup Function allows you to consistently mask data when you use the same source and lookup tables in any environment.


2 Answers

The hashtable hashes your key and put it in array.

For example, hash(x) = 3, where x is your key. The table then puts it into array[3]. Accessing from array is O(1).

like image 125
ggbranch Avatar answered Oct 22 '22 07:10

ggbranch


At a minimum, hash tables consist of an array and hash function. When an object is added to the table, the hash function is computed on the object and it is stored in the array at the index of the corresponding value that was computed. e.g., if hash(obj) = 2 then arr[2] = obj.

The average insert/lookup on a hash table is O(1).

However it is possible to have collisions when objects compute the same hash value.

In the general case there are "buckets" at each index of the array to handle these collisions. Meaning, all three objects are stored in some other data structure (maybe a linked list or another array) at the index of the hash table.

Therefore, the worst case for lookup on a hash table is O(n) because it is possible that all objects stored in the hash table have collided and are stored in the same bucket.

like image 40
Chris Dargis Avatar answered Oct 22 '22 05:10

Chris Dargis