Why is accessing an element of a dictionary by key O(1) even though the hash function may not be O(1)?
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.
the
HashFunc
itself has a lot of operations behind the scenes
That is certainly true. However, the number of these operations depends on the size of the key, not on the size of the hash table into which the key is inserted: the number of operations to compute hash function is the same for a key in a table with ten or with ten thousand entries.
That is why the call of hash function is often considered O(1). This works fine for fixed-size keys (integral values and fixed-length strings). It also provides a decent approximation for variable-sized keys with a practical upper limit.
Generally, though, access time of a hash table is O(k), where k
is the upper limit on the size of the hash key.
It means that no matter what size your collection can be, it will still take almost the same amount of time to retrieve any of its members.
So in other words Dictionary with 5 members will let's say coud take around 0.002 ms to access one of them, as well as dictionary of 25 members should take something similar. Big O means algorithmic complexity over collection size instead of actual statements or functions executed
If a dictionary/map is implemented as a HashMap
, it has a best case complexity of O(1)
, since i best case it requires exactly the calculation of the hash-code of the key element for retrieval, if there are no key collisions.
A hash-map may have a worst-case runtime complexity of O(n)
if you have a lot of key collisions or a very bad hash function, since in this case it degrades to a linear scan of the entire array which holds the data.
Also, O(1)
doesn't mean instantly, it means it has a constant amount. So choosing the right implementation for a dictionary may as well depend on the number of elements in the collection, since having a very high constant cost for the function will be much worse if there are only a few entries.
That's why dictionaryies/maps are implemented differently for different scenarios. For Java there are multiple different implementations, C++ uses red/black-trees, etc. You chose them based on the number of data and based on their best/average/worst-case runtime-efficiency.
Theoretically it is still O(n), because in the worst case all your data may end up having identical hash and be bundled together in which case you have to linearly go through all of it.