Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is accessing an element of a dictionary by key O(1) even though the hash function may not be O(1)?

I see how you can access your collection by key. However, the hash function itself has a lot of operations behind the scenes, doesn't it?

Assuming you have a nice hash function which is very efficient, it still may take many operations.

Can this be explained?

like image 643
monogate Avatar asked May 20 '16 13:05

monogate


People also ask

What is the big O time complexity to find an item in a dictionary?

If we explain the difference by Big O concepts, dictionaries have constant time complexity, O(1) while lists have linear time complexity, O(n).

Are Python dictionaries O 1?

Python's dictionary implementation reduces the average complexity of dictionary lookups to O(1) by requiring that key objects provide a "hash" function. Such a hash function takes the information in a key object and uses it to produce an integer, called a hash value.

What is the big O of hash table?

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 is a hash lookup O 1?

Each time we insert data, it takes O(1) time to insert it (since the hash function is O(1). Looking up data is the same. If we want to find a value, x, we have only to find out h(x), which tells us where x is located in the hash table. So we can look up any hash value in O(1) as well.


1 Answers

O(1) doesn't mean instant. O(1) means constant without regard to the size of the data. The hash function takes a certain amount of time, but that amount of time doesn't scale with the size of the collection.

like image 93
Paarth Avatar answered Oct 04 '22 03:10

Paarth